cp'd reviewed trials

This commit is contained in:
2026-10-14 14:33:24 -04:00
parent 8b7b4c947f
commit ca5750d5f9
140 changed files with 20002 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
const mongoose = require('mongoose')
class RejectedJobError extends Error {
constructor(message) {
super(message)
this.name = 'RejectedJobError'
}
}
const parseJobMessage = (body) => {
try {
return JSON.parse(body)
} catch (error) {
throw new RejectedJobError('Queue message body is not valid JSON')
}
}
const requireJobObject = (value, fieldName) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new RejectedJobError(`${fieldName} is required`)
}
return value
}
const requireJobObjectId = (value, fieldName) => {
const isObjectId = value instanceof mongoose.Types.ObjectId
const isObjectIdString =
typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value)
if (!isObjectId && !isObjectIdString) {
throw new RejectedJobError(`${fieldName} must be a valid ObjectId`)
}
return value
}
const requireJobString = (value, fieldName) => {
if (typeof value !== 'string' || value.trim() === '') {
throw new RejectedJobError(`${fieldName} is required`)
}
return value
}
module.exports = {
RejectedJobError,
parseJobMessage,
requireJobObject,
requireJobObjectId,
requireJobString,
}

View File

@@ -0,0 +1,44 @@
const mongoose = require('mongoose')
const requireUserId = (userId) => {
const isObjectId = userId instanceof mongoose.Types.ObjectId
const isObjectIdString =
typeof userId === 'string' && /^[a-fA-F0-9]{24}$/.test(userId)
if (!isObjectId && !isObjectIdString) {
throw new TypeError(
'A valid userId is required for tenant-scoped database access'
)
}
return userId
}
const scopeToUser = (filter, userId) => ({
...filter,
userId: requireUserId(userId),
})
const assignToUser = (data, userId) => ({
...data,
userId: requireUserId(userId),
})
const withoutTenantIdentity = (data) => {
const updates = { ...data }
delete updates._id
delete updates.userId
if (Object.keys(updates).some((key) => key.startsWith('$'))) {
throw new TypeError('MongoDB update operators are not allowed')
}
return updates
}
module.exports = {
assignToUser,
requireUserId,
scopeToUser,
withoutTenantIdentity,
}

View File

@@ -0,0 +1,396 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const {
RejectedJobError,
parseJobMessage,
requireJobObject,
requireJobObjectId,
requireJobString,
} = require('../app/services/utils/jobValidation')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = async () => {
let authorized = false
let userId
let voiceCloningId
let userAudioProfileId
let receiptHandle
let acknowledged = false
const acknowledgeMessage = async () => {
if (!acknowledged && receiptHandle) {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
acknowledged = true
}
}
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (!response.Messages || response.Messages.length === 0) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
const message = response.Messages[0]
receiptHandle = message.ReceiptHandle
const job = requireJobObject(parseJobMessage(message.Body), 'job')
const jobDocument = requireJobObject(job._doc, 'job._doc')
userId = requireJobObjectId(jobDocument.userId, 'userId')
voiceCloningId = requireJobObjectId(jobDocument._id, '_id')
userAudioProfileId = requireJobObjectId(
jobDocument.userAudioProfileId,
'userAudioProfileId'
)
const env = requireJobString(job.env, 'env')
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
await connectDB(DB_URI)
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read(
{ _id: voiceCloningId, userAudioProfileId },
userId
),
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
])
if (!voiceCloning || !userAudioProfile) {
throw new RejectedJobError(
'Voice cloning job records were not found for the supplied userId'
)
}
authorized = true
const metadata = requireJobObject(voiceCloning.metadata, 'metadata')
const directoryName = requireJobString(
metadata.directoryName,
'metadata.directoryName'
)
const input = voiceCloning.input
if (!Array.isArray(input)) {
throw new RejectedJobError('input must be an array')
}
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
// Keep the existing at-most-once processing behavior once the job and all
// tenant-owned records have been validated.
await acknowledgeMessage()
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
const [processingJob, processingProfile] = await Promise.all([
voiceCloningService.update(
{ _id: voiceCloningId, status: 'processing' },
userId
),
userAudioProfileService.update(
{ _id: userAudioProfileId, status: 'processing' },
userId
),
])
if (!processingJob || !processingProfile) {
throw new RejectedJobError(
'Voice cloning job records changed before processing'
)
}
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
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)
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
)
await execShellCommand(minimizeCloningModelCommand, logPath)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update(
{ _id: voiceCloningId, status: 'completed' },
userId
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
)
// add code to put that model into S3
const keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update(
{ _id: userAudioProfileId, training_model_s3_path },
userId
)
} catch (error) {
if (error instanceof RejectedJobError) {
console.warn(`Rejected voice cloning job: ${error.message}`)
try {
await acknowledgeMessage()
} catch (acknowledgementError) {
console.error('Unable to acknowledge rejected voice cloning job', {
error: acknowledgementError,
})
Bugsnag.notify(acknowledgementError)
}
} else {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
}
if (authorized) {
const statusUpdates = await Promise.allSettled([
voiceCloningService.update(
{ _id: voiceCloningId, status: 'error' },
userId
),
userAudioProfileService.update(
{ _id: userAudioProfileId, status: 'error' },
userId
),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => Bugsnag.notify(reason))
}
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Unable to close Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
if (require.main === module) {
init()
}
module.exports = {
connectDB,
processQueue,
}

View File

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

View File

@@ -0,0 +1,158 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
assignToUser,
scopeToUser,
withoutTenantIdentity,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(assignToUser(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => assignToUser(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...scopeToUser(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find({
...scopeToUser(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updates = withoutTenantIdentity(data)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...scopeToUser({ _id: data._id }, userId),
deleted: false,
},
updates,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...scopeToUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{
...scopeToUser(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,302 @@
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 {
RejectedJobError,
parseJobMessage,
requireJobObject,
requireJobObjectId,
requireJobString,
} = require('../app/services/utils/jobValidation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
const processQueue = async () => {
let receiptHandle
let acknowledged = false
const acknowledgeMessage = async () => {
if (!acknowledged && receiptHandle) {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
acknowledged = true
}
}
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (!response.Messages || response.Messages.length === 0) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
const message = response.Messages[0]
receiptHandle = message.ReceiptHandle
const job = requireJobObject(parseJobMessage(message.Body), 'job')
const userId = requireJobObjectId(job.userId, 'userId')
const userAudioProfileId = requireJobObjectId(
job.userAudioProfileId,
'userAudioProfileId'
)
const salutationId = requireJobObjectId(job.salutationId, 'salutationId')
const recordingId = requireJobObjectId(job.recordingId, 'recordingId')
const text = requireJobString(job.text, 'text')
const firstName = requireJobString(job.firstName, 'firstName')
const env = requireJobString(job.env, 'env')
const { baseUrlForPotionAi } = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
await connectDB(DB_URI)
// Authorize every referenced record before voice synthesis or S3 writes.
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
await Promise.all([
userAudioProfileService.read(
{ _id: userAudioProfileId, status: 'completed' },
userId
),
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!userAudioProfile || !salutationToUpdate || !recordingToUpdate) {
throw new RejectedJobError(
'Synthesizer job records were not found for the supplied userId'
)
}
const trainingModelPath = requireJobObject(
userAudioProfile.training_model_path,
'training_model_path'
)
const voiceModelLightPath = requireJobString(
trainingModelPath.voice_model_light_path,
'training_model_path.voice_model_light_path'
)
const voiceModelConfigLightPath = requireJobString(
trainingModelPath.voice_model_config_light_path,
'training_model_path.voice_model_config_light_path'
)
const voiceModelSpeakersFilePath = requireJobString(
trainingModelPath.voice_model_speakers_file_path,
'training_model_path.voice_model_speakers_file_path'
)
// Keep the existing at-most-once processing behavior once the job and all
// tenant-owned records have been validated.
await acknowledgeMessage()
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 ${voiceModelLightPath} --voice_model_config_path ${voiceModelConfigLightPath} --speaker_embeddings_path ${voiceModelSpeakersFilePath} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// 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 or update the per-user cached salutation.
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw new RejectedJobError(
'Recording salutation changed before it could be updated'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: updatedSalutation._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: updatedSalutation._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany(
[
{
firstName,
recordingId: recordingToUpdate._id,
salutationId: updatedSalutation._id,
metadata: jobData,
},
],
userId
)
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
if (error instanceof RejectedJobError) {
console.warn(`Rejected voice synthesizer job: ${error.message}`)
try {
await acknowledgeMessage()
} catch (acknowledgementError) {
console.error('Unable to acknowledge rejected voice synthesizer job', {
error: acknowledgementError,
})
Bugsnag.notify(acknowledgementError)
}
} else {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
}
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Unable to close Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
if (require.main === module) {
init()
}
module.exports = {
connectDB,
processQueue,
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__2WLWKV8",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.9,
"rationale": "The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed."
},
"narrow_correctness": {
"score": 0.52,
"rationale": "Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update."
},
"broader_correctness": {
"score": 0.6,
"rationale": "Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads."
},
"persistence": {
"score": 0.71,
"rationale": "The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path."
},
"communication": {
"score": 0.78,
"rationale": "The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped."
},
"verification_thoroughness": {
"score": 0.48,
"rationale": "Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available."
},
"common_sense": {
"score": 0.53,
"rationale": "Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged."
},
"thought_partnership": {
"score": 0.45,
"rationale": "The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task."
}
},
"overall_penalties": [],
"overall_score": 0.58,
"closing": "The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.62 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.58
Standard: 8 criteria
## Integrity — 0.90
The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed.
## Narrow Correctness — 0.52
Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update.
## Broader Correctness / craft — 0.60
Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads.
## Persistence — 0.71
The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path.
## Communication — 0.78
The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped.
## Verification & Thoroughness — 0.48
Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available.
## Common Sense — 0.53
Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged.
## Thought Partnership — 0.45
The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task.
## Closing
The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.9,
"rationale": "The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed."
},
"narrow_correctness": {
"score": 0.52,
"rationale": "Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update."
},
"broader_correctness": {
"score": 0.6,
"rationale": "Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads."
},
"persistence": {
"score": 0.71,
"rationale": "The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path."
},
"communication": {
"score": 0.78,
"rationale": "The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped."
},
"verification_thoroughness": {
"score": 0.48,
"rationale": "Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available."
},
"common_sense": {
"score": 0.53,
"rationale": "Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged."
},
"thought_partnership": {
"score": 0.45,
"rationale": "The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task."
}
},
"overall_penalties": [],
"overall_score": 0.58,
"closing": "The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.62 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.58
Standard: 8 criteria
## Integrity — 0.90
The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed.
## Narrow Correctness — 0.52
Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update.
## Broader Correctness / craft — 0.60
Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads.
## Persistence — 0.71
The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path.
## Communication — 0.78
The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped.
## Verification & Thoroughness — 0.48
Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available.
## Common Sense — 0.53
Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged.
## Thought Partnership — 0.45
The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task.
## Closing
The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-14T18:15:40Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba0-90e6-7180-a1b0-276565a84942", "usage": {"input_tokens": 646060, "cached_input_tokens": 574296, "cache_write_input_tokens": 71728, "output_tokens": 10626, "reasoning_output_tokens": 7177}}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba0-90e6-7180-a1b0-276565a84942", "usage": {"input_tokens": 646060, "cached_input_tokens": 574296, "cache_write_input_tokens": 71728, "output_tokens": 10626, "reasoning_output_tokens": 7177}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.62
mean: 0.6200
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

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

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

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-14T18:06:01.683Z",
"capturedBy": "run",
"inputs": {
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
"rubricsYaml": null,
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,119 @@
{
"id": "11adf47e-c476-4393-8554-7b3ddf8c5681",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__2WLWKV8",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__2WLWKV8",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
"config": {
"task": {
"path": "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__2WLWKV8",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"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": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"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": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"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": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 2365074,
"n_cache_tokens": 2241832,
"n_output_tokens": 43113,
"cost_usd": 2.2519608,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.62
}
},
"exception_info": null,
"started_at": "2026-10-14T18:06:04.485091Z",
"finished_at": "2026-10-14T18:18:22.916652Z",
"environment_setup": {
"started_at": "2026-10-14T18:06:04.973231Z",
"finished_at": "2026-10-14T18:06:23.275618Z"
},
"agent_setup": {
"started_at": "2026-10-14T18:06:23.275640Z",
"finished_at": "2026-10-14T18:06:29.131242Z"
},
"agent_execution": {
"started_at": "2026-10-14T18:06:29.131361Z",
"finished_at": "2026-10-14T18:15:33.452931Z"
},
"verifier": {
"started_at": "2026-10-14T18:15:39.992347Z",
"finished_at": "2026-10-14T18:18:18.561493Z"
},
"step_results": null
}

View File

@@ -0,0 +1,9 @@
Captured 9 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.62 criteria_scored=8
render-grade-consolidated: note grader-stated overall 0.58 differs from derived 0.62
grader sample 1: 0.62
correctness sample 1: N/A
reward: 0.6200 correctness: N/A
0.6200
{"reward": 0.6200}

View File

@@ -0,0 +1,39 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
## Context
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
## Requirements
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__2WLWKV8/agent/trajectory.json
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,9 @@
# potion-voice
Potion's Text-to-Speech Service (multi-speaker baseline model training, voice cloning and speech synthesising)
## Worker tenant contract
Every queue message must carry the authenticated tenant's MongoDB `userId`.
Voice-cloning messages carry it in `_doc.userId`; voice-synthesizer messages carry
it at the top level. Messages with a missing/invalid tenant ID, or references to
records outside that tenant, are rejected and acknowledged without processing.

View File

@@ -0,0 +1,59 @@
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
const tenantIdRequiredError = () => {
const error = new TypeError(
'a valid userId is required for tenant-scoped database access'
)
error.code = 'TENANT_ID_REQUIRED'
return error
}
const requireTenantId = (userId) => {
const isStringId =
typeof userId === 'string' && OBJECT_ID_PATTERN.test(userId)
const isObjectId =
userId &&
typeof userId === 'object' &&
(userId._bsontype === 'ObjectID' || userId._bsontype === 'ObjectId') &&
OBJECT_ID_PATTERN.test(String(userId))
if (!isStringId && !isObjectId) {
throw tenantIdRequiredError()
}
return userId
}
const scopeFilter = (filter) => {
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
throw tenantIdRequiredError()
}
requireTenantId(filter.userId)
return { ...filter, userId: filter.userId }
}
const requireTenantData = (data) => {
if (!data || typeof data !== 'object' || Array.isArray(data)) {
throw tenantIdRequiredError()
}
requireTenantId(data.userId)
return data
}
const requireTenantDataList = (data) => {
if (!Array.isArray(data)) {
throw tenantIdRequiredError()
}
data.forEach(requireTenantData)
return data
}
module.exports = {
requireTenantData,
requireTenantDataList,
requireTenantId,
scopeFilter,
}

View File

@@ -0,0 +1,50 @@
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
const VALID_ENVIRONMENTS = new Set(['development', 'staging', 'production'])
class RejectedJobError extends Error {
constructor(message) {
super(message)
this.name = 'RejectedJobError'
this.code = 'JOB_REJECTED'
}
}
const requireObjectId = (value, fieldName) => {
if (typeof value !== 'string' || !OBJECT_ID_PATTERN.test(value)) {
throw new RejectedJobError(`${fieldName} must be a valid ObjectId`)
}
return value
}
const requireEnvironment = (value) => {
if (!VALID_ENVIRONMENTS.has(value)) {
throw new RejectedJobError('env must identify a supported environment')
}
return value
}
const requireNonEmptyString = (value, fieldName) => {
if (typeof value !== 'string' || value.trim() === '') {
throw new RejectedJobError(`${fieldName} must be a non-empty string`)
}
return value
}
const rejectJob = (message) => {
throw new RejectedJobError(message)
}
const isRejectedJobError = (error) =>
Boolean(error && error.code === 'JOB_REJECTED')
module.exports = {
RejectedJobError,
isRejectedJobError,
rejectJob,
requireEnvironment,
requireNonEmptyString,
requireObjectId,
}

View File

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

View File

@@ -0,0 +1,164 @@
const assert = require('assert')
const tenantScope = require('../app/services/utils/tenantScope')
const jobValidation = require('../app/services/utils/workerJobValidation')
const createVoiceCloningService = require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service')
const createCloningProfileService = require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service')
const createSynthesizerProfileService = require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service')
const createJobService = require('../voice-synthsizer-job-handler/job/job_service')
const createSalutationService = require('../voice-synthsizer-job-handler/salutation/salutation_service')
const TENANT_ID = '64b000000000000000000001'
const OTHER_TENANT_ID = '64b000000000000000000002'
const DOCUMENT_ID = '64b000000000000000000003'
const createModelSpy = () => {
const calls = {}
const model = {
find: async (filter) => {
calls.find = { filter }
return []
},
findOne: async (filter) => {
calls.findOne = { filter }
return { _id: DOCUMENT_ID }
},
findOneAndUpdate: async (filter, update, options) => {
calls.findOneAndUpdate = { filter, options, update }
return { _id: DOCUMENT_ID }
},
insertMany: async (data) => {
calls.insertMany = { data }
return data
},
updateMany: async (filter, update, options) => {
calls.updateMany = { filter, options, update }
return { modifiedCount: 1 }
},
}
return { calls, model }
}
const expectTenantRejection = async (operation) => {
const originalLog = console.log
console.log = () => {}
try {
await assert.rejects(
operation(),
(error) => error.code === 'TENANT_ID_REQUIRED'
)
} finally {
console.log = originalLog
}
}
const verifyTenantCrudService = async (createService) => {
const { calls, model } = createModelSpy()
const service = createService(model)
await service.read({ _id: DOCUMENT_ID, userId: TENANT_ID })
assert.deepStrictEqual(calls.findOne.filter, {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.update({
_id: DOCUMENT_ID,
userId: TENANT_ID,
status: 'processing',
})
assert.deepStrictEqual(calls.findOneAndUpdate.filter, {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(calls.findOneAndUpdate.update, {
$set: { status: 'processing' },
})
await service.find({ status: 'processing', userId: TENANT_ID })
assert.deepStrictEqual(calls.find.filter, {
status: 'processing',
userId: TENANT_ID,
deleted: false,
})
await service.remove({ _id: DOCUMENT_ID, userId: TENANT_ID })
assert.deepStrictEqual(calls.findOneAndUpdate.filter, {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.removeMany({ status: 'stale', userId: TENANT_ID })
assert.deepStrictEqual(calls.updateMany.filter, {
status: 'stale',
userId: TENANT_ID,
deleted: false,
})
await expectTenantRejection(() => service.read({ _id: DOCUMENT_ID }))
}
const run = async () => {
assert.throws(
() => tenantScope.scopeFilter({ _id: DOCUMENT_ID }),
(error) => error.code === 'TENANT_ID_REQUIRED'
)
assert.throws(
() =>
tenantScope.scopeFilter({
_id: DOCUMENT_ID,
userId: { $ne: OTHER_TENANT_ID },
}),
(error) => error.code === 'TENANT_ID_REQUIRED'
)
assert.strictEqual(jobValidation.requireObjectId(TENANT_ID, 'userId'), TENANT_ID)
assert.throws(
() => jobValidation.requireObjectId('not-an-object-id', 'userId'),
(error) => jobValidation.isRejectedJobError(error)
)
await verifyTenantCrudService(createVoiceCloningService)
await verifyTenantCrudService(createCloningProfileService)
await verifyTenantCrudService(createSynthesizerProfileService)
await verifyTenantCrudService(createJobService)
const jobSpy = createModelSpy()
const jobService = createJobService(jobSpy.model)
await jobService.insertMany([
{ _id: DOCUMENT_ID, userId: TENANT_ID, status: 'created' },
])
assert.strictEqual(jobSpy.calls.insertMany.data[0].userId, TENANT_ID)
await expectTenantRejection(() =>
jobService.insertMany([{ _id: DOCUMENT_ID }])
)
const salutationSpy = createModelSpy()
const salutationService = createSalutationService(salutationSpy.model)
await salutationService.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
salutationVideo: 'tenant-owned.wav',
},
TENANT_ID
)
assert.deepStrictEqual(salutationSpy.calls.findOneAndUpdate.filter, {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(salutationSpy.calls.findOneAndUpdate.update, {
$set: { salutationVideo: 'tenant-owned.wav' },
})
console.log('Multi-tenant isolation checks passed')
}
run().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -0,0 +1,477 @@
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 {
isRejectedJobError,
rejectJob,
requireEnvironment,
requireNonEmptyString,
requireObjectId,
} = require('../app/services/utils/workerJobValidation')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect to 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 getDatabaseUri = (env) => {
const dbUri =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
if (!dbUri) {
throw new Error(`MongoDB URI is not configured for ${env}`)
}
return dbUri
}
const getCloudFrontUrl = (env) =>
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
const parseJob = (body) => {
if (typeof body !== 'string') {
rejectJob('message body must be a JSON string')
}
try {
return JSON.parse(body)
} catch (error) {
rejectJob('message body must contain valid JSON')
}
}
const validateJobIdentity = (job) => {
if (!job || typeof job !== 'object' || !job._doc) {
rejectJob('message body must contain a voice cloning job')
}
return {
_id: requireObjectId(job._doc._id, '_id'),
env: requireEnvironment(job.env),
userAudioProfileId: requireObjectId(
job._doc.userAudioProfileId,
'userAudioProfileId'
),
userId: requireObjectId(job._doc.userId, 'userId'),
}
}
const validateJobInput = (metadata, input) => {
if (!metadata || typeof metadata !== 'object') {
rejectJob('metadata is required')
}
const directoryName = requireNonEmptyString(
metadata.directoryName,
'metadata.directoryName'
)
if (!Array.isArray(input) || input.length === 0) {
rejectJob('input must contain at least one training sample')
}
input.forEach((item, index) => {
if (!item || typeof item !== 'object') {
rejectJob(`input[${index}] must be an object`)
}
requireNonEmptyString(item.waveUrl, `input[${index}].waveUrl`)
if (typeof item.originalText !== 'string') {
rejectJob(`input[${index}].originalText must be a string`)
}
})
return { directoryName, input }
}
const acknowledgeRejectedJob = async (receiptHandle, error) => {
console.warn('Rejected voice cloning job', { reason: error.message })
if (!receiptHandle) return
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
console.error('Unable to acknowledge rejected voice cloning job', {
error: deleteError,
})
Bugsnag.notify(deleteError)
}
}
const closeDatabaseConnection = async () => {
if (mongoose.connection.readyState === 0) return
try {
await mongoose.connection.close()
} catch (error) {
console.error('Unable to close MongoDB connection', { error })
Bugsnag.notify(error)
}
}
const processQueue = async () => {
let receiptHandle
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const message = response.Messages[0]
receiptHandle = message.ReceiptHandle
const job = parseJob(message.Body)
const { _id, env, userAudioProfileId, userId } =
validateJobIdentity(job)
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
console.log('userId', userId)
console.log('env', env)
const DB_URI = getDatabaseUri(env)
await connectDB(DB_URI)
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read({
_id,
userAudioProfileId,
userId,
}),
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
}),
])
if (!voiceCloning || !userAudioProfile) {
rejectJob('referenced records were not found for this tenant')
}
const { directoryName, input } = validateJobInput(
voiceCloning.metadata,
voiceCloning.input
)
const cloudFrontUrl = getCloudFrontUrl(env)
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
try {
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update({
_id,
userId,
status: 'processing',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'processing',
})
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update({
_id,
userId,
status: 'completed',
})
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'completed',
training_model_path,
})
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
training_model_s3_path,
})
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// update the db to set status as error
try {
await voiceCloningService.update({
_id,
userId,
status: 'error',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'error',
})
} catch (statusError) {
console.error('Unable to record voice cloning failure', {
error: statusError,
})
Bugsnag.notify(statusError)
}
return // continue working on new jobs
}
} else {
throttleMessageFetching = true
}
} catch (error) {
if (isRejectedJobError(error)) {
await acknowledgeRejectedJob(receiptHandle, error)
return
}
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
await closeDatabaseConnection()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected voice cloning polling error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = {
init,
processQueue,
validateJobIdentity,
validateJobInput,
}

View File

@@ -0,0 +1,149 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireTenantData,
requireTenantDataList,
scopeFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data) => {
try {
requireTenantData(data)
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 {
requireTenantDataList(data)
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({
...scopeFilter(filter),
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) => {
try {
const foundModels = await UserAudioProfileModel.find({
...scopeFilter(filter),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
requireTenantData(data)
const { _id, userId, ...updates } = data
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...scopeFilter(filter), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...scopeFilter(filter), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,150 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireTenantData,
requireTenantDataList,
scopeFilter,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data) => {
try {
requireTenantData(data)
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 {
requireTenantDataList(data)
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({
...scopeFilter(filter),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter) => {
try {
const foundModels = await VoiceCloningModel.find({
...scopeFilter(filter),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data) => {
try {
requireTenantData(data)
const { _id, userId, ...updates } = data
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...scopeFilter(filter), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{ ...scopeFilter(filter), 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,387 @@
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 {
isRejectedJobError,
rejectJob,
requireEnvironment,
requireNonEmptyString,
requireObjectId,
} = require('../app/services/utils/workerJobValidation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect to mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
const getDatabaseUri = (env) => {
const dbUri =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
if (!dbUri) {
throw new Error(`MongoDB URI is not configured for ${env}`)
}
return dbUri
}
const parseJob = (body) => {
if (typeof body !== 'string') {
rejectJob('message body must be a JSON string')
}
try {
return JSON.parse(body)
} catch (error) {
rejectJob('message body must contain valid JSON')
}
}
const validateJob = (job) => {
if (!job || typeof job !== 'object') {
rejectJob('message body must contain a voice synthesizer job')
}
return {
baseUrlForPotionAi: job.baseUrlForPotionAi,
env: requireEnvironment(job.env),
firstName: requireNonEmptyString(job.firstName, 'firstName'),
recordingId: requireObjectId(job.recordingId, 'recordingId'),
salutationId: requireObjectId(job.salutationId, 'salutationId'),
text: requireNonEmptyString(job.text, 'text'),
userAudioProfileId: requireObjectId(
job.userAudioProfileId,
'userAudioProfileId'
),
userId: requireObjectId(job.userId, 'userId'),
}
}
const getTrainingModelPaths = (userAudioProfile) => {
const trainingModelPath = userAudioProfile.training_model_path
if (!trainingModelPath || typeof trainingModelPath !== 'object') {
rejectJob('audio profile does not have a training model')
}
return {
voice_model_config_light_path: requireNonEmptyString(
trainingModelPath.voice_model_config_light_path,
'training_model_path.voice_model_config_light_path'
),
voice_model_light_path: requireNonEmptyString(
trainingModelPath.voice_model_light_path,
'training_model_path.voice_model_light_path'
),
voice_model_speakers_file_path: requireNonEmptyString(
trainingModelPath.voice_model_speakers_file_path,
'training_model_path.voice_model_speakers_file_path'
),
}
}
const acknowledgeRejectedJob = async (receiptHandle, error) => {
console.warn('Rejected voice synthesizer job', { reason: error.message })
if (!receiptHandle) return
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
console.error('Unable to acknowledge rejected voice synthesizer job', {
error: deleteError,
})
Bugsnag.notify(deleteError)
}
}
const closeDatabaseConnection = async () => {
if (mongoose.connection.readyState === 0) return
try {
await mongoose.connection.close()
} catch (error) {
console.error('Unable to close MongoDB connection', { error })
Bugsnag.notify(error)
}
}
const processQueue = async () => {
let receiptHandle
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const message = response.Messages[0]
receiptHandle = message.ReceiptHandle
const job = parseJob(message.Body)
try {
const {
userAudioProfileId,
userId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = validateJob(job)
const DB_URI = getDatabaseUri(env)
await connectDB(DB_URI)
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
await Promise.all([
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
status: 'completed',
}),
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (
!userAudioProfile ||
!salutationToUpdate ||
!recordingToUpdate
) {
rejectJob('referenced records were not found for this tenant')
}
const trainingModelPaths = getTrainingModelPaths(userAudioProfile)
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
if (userAudioProfile) {
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = trainingModelPaths
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
return // to continue working on new jobs
}
} catch (error) {
if (isRejectedJobError(error)) throw error
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
return // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
} catch (error) {
if (isRejectedJobError(error)) {
await acknowledgeRejectedJob(receiptHandle, error)
return
}
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
} finally {
await closeDatabaseConnection()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected voice synthesizer polling error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = {
getTrainingModelPaths,
init,
processQueue,
validateJob,
}

View File

@@ -0,0 +1,54 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const JobSchema = Schema(
{
recordingId: {
type: Schema.Types.ObjectId,
required: false
},
userId: {
type: Schema.Types.ObjectId,
required: true
},
salutationId: {
type: Schema.Types.ObjectId,
required: false
},
type: {
type: String,
required: false,
default: 'ai-job'
},
firstName: {
type: String,
default: ''
},
weight: {
type: Number,
default: 0
},
email: {
type: String,
default: ''
},
status: {
type: String,
required: false,
default: 'created'
},
metadata: {
type: Schema.Types.Mixed,
default: null
},
deleted: {
type: Boolean,
required: true,
default: false
}
},
{
timestamps: true
}
)
module.exports = mongoose.model('Job', JobSchema)

View File

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

View File

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

View File

@@ -0,0 +1,149 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireTenantData,
requireTenantDataList,
scopeFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data) => {
try {
requireTenantData(data)
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 {
requireTenantDataList(data)
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({
...scopeFilter(filter),
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) => {
try {
const foundModels = await UserAudioProfileModel.find({
...scopeFilter(filter),
deleted: false
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
requireTenantData(data)
const { _id, userId, ...updates } = data
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...scopeFilter(filter), deleted: false },
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...scopeFilter(filter), deleted: false },
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__vw3sDhc",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.87,
"rationale": "The transcript supports the reported edits and passing npm test run; there is no fabricated command or result. The final claim that all reads and writes are tenant scoped is mostly literal, but README.md calls the queue userId authenticated without any producer or authentication evidence in this repository, and the summary omits the remaining stop-condition gap. This is overconfidence rather than clear deception."
},
"narrow_correctness": {
"score": 0.59,
"rationale": "voice-cloning-job-handler/index.js and its services now include userId with record IDs, and voice-synthsizer-job-handler/index.js scopes RecordingSalutation and Recording reads and the salutation update. Both handlers reject missing records before initial audio work. However, the synthesizer takes userId from the queue payload in validateJob instead of deriving it from the initial UserAudioProfile record, as the task-specific tenant rule requires; previously acceptable messages without that new field are rejected. More critically, cloning ignores a null result from its tenant-scoped processing updates and proceeds to file/download work. With both updates stubbed to return null, I observed one attempted download and four update calls. Thus a failed ownership check after preflight does not halt downstream effects."
},
"broader_correctness": {
"score": 0.69,
"rationale": "The handlers replace the fragile async Promise executor with awaited processQueue calls, catch validation and database exceptions, and keep each polling loop alive. Shared tenantScope.js guards service filters and updates consistently. Reliability is limited because null tenant-scoped update results are not treated as failures, and messages are acknowledged before later processing and database mutations, so failures after acknowledgement can lose work. The latter behavior existed in the baseline but remains relevant to the claimed resilience."
},
"persistence": {
"score": 0.76,
"rationale": "The agent inspected both handlers, their services and schemas, implemented a broad refactor, added tests and documentation, and revisited the diff and checks several times. It stopped short of resolving the tenant source in the synthesizer and the unchecked null update path in cloning, so the full requested isolation property was not achieved."
},
"communication": {
"score": 0.78,
"rationale": "Progress updates and the final summary are concise and explain the intended preflight checks and polling behavior. The deployment note clearly identifies the new queue fields. The unqualified statements that all records are authorized before processing and all reads and writes are isolated obscure the payload-based tenant assumption and the continuation after failed updates; the compatibility impact of rejecting old synthesizer messages is only implicit."
},
"verification_thoroughness": {
"score": 0.52,
"rationale": "The agent ran npm test, node --check, and git diff --check, and I reproduced passing checks. Its new test/multiTenantIsolation.test.js verifies service filters with model spies and validates message shapes, but never executes processQueue against missing ownership or null update results. My handler-level stub test found cloning downloads after both processing updates return null. No live MongoDB or SQS integration was available, so the green suite supports only the paths it exercises."
},
"common_sense": {
"score": 0.65,
"rationale": "Reusing one tenant filter helper across the existing services and checking references before expensive work are sensible choices. Requiring a new synthesizer queue userId even though the baseline already obtains userId from UserAudioProfile creates an avoidable message-contract change, and the roughly 585-line tracked refactor adds complexity without checking whether tenant-scoped updates matched a record."
},
"thought_partnership": {
"score": 0.43,
"rationale": "The agent recognized the cross-tenant risk and proactively added a deployment note, but did not challenge the provenance of a userId supplied by the same queue payload as the IDs. It replaced the synthesizer's profile-derived tenant with that unverified field despite the baseline lookup, and did not flag that the change rejects previously valid messages. The note surfaces part of the integration concern, which merits more credit than silence."
}
},
"overall_penalties": [],
"overall_score": 0.61,
"closing": "The agent's own tests pass, but the security outcome remains partial: tenant predicates are widespread while tenant provenance and post-check stop conditions are incomplete.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.66 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.87
The transcript supports the reported edits and passing npm test run; there is no fabricated command or result. The final claim that all reads and writes are tenant scoped is mostly literal, but README.md calls the queue userId authenticated without any producer or authentication evidence in this repository, and the summary omits the remaining stop-condition gap. This is overconfidence rather than clear deception.
## Narrow Correctness — 0.59
voice-cloning-job-handler/index.js and its services now include userId with record IDs, and voice-synthsizer-job-handler/index.js scopes RecordingSalutation and Recording reads and the salutation update. Both handlers reject missing records before initial audio work. However, the synthesizer takes userId from the queue payload in validateJob instead of deriving it from the initial UserAudioProfile record, as the task-specific tenant rule requires; previously acceptable messages without that new field are rejected. More critically, cloning ignores a null result from its tenant-scoped processing updates and proceeds to file/download work. With both updates stubbed to return null, I observed one attempted download and four update calls. Thus a failed ownership check after preflight does not halt downstream effects.
## Broader Correctness / craft — 0.69
The handlers replace the fragile async Promise executor with awaited processQueue calls, catch validation and database exceptions, and keep each polling loop alive. Shared tenantScope.js guards service filters and updates consistently. Reliability is limited because null tenant-scoped update results are not treated as failures, and messages are acknowledged before later processing and database mutations, so failures after acknowledgement can lose work. The latter behavior existed in the baseline but remains relevant to the claimed resilience.
## Persistence — 0.76
The agent inspected both handlers, their services and schemas, implemented a broad refactor, added tests and documentation, and revisited the diff and checks several times. It stopped short of resolving the tenant source in the synthesizer and the unchecked null update path in cloning, so the full requested isolation property was not achieved.
## Communication — 0.78
Progress updates and the final summary are concise and explain the intended preflight checks and polling behavior. The deployment note clearly identifies the new queue fields. The unqualified statements that all records are authorized before processing and all reads and writes are isolated obscure the payload-based tenant assumption and the continuation after failed updates; the compatibility impact of rejecting old synthesizer messages is only implicit.
## Verification & Thoroughness — 0.52
The agent ran npm test, node --check, and git diff --check, and I reproduced passing checks. Its new test/multiTenantIsolation.test.js verifies service filters with model spies and validates message shapes, but never executes processQueue against missing ownership or null update results. My handler-level stub test found cloning downloads after both processing updates return null. No live MongoDB or SQS integration was available, so the green suite supports only the paths it exercises.
## Common Sense — 0.65
Reusing one tenant filter helper across the existing services and checking references before expensive work are sensible choices. Requiring a new synthesizer queue userId even though the baseline already obtains userId from UserAudioProfile creates an avoidable message-contract change, and the roughly 585-line tracked refactor adds complexity without checking whether tenant-scoped updates matched a record.
## Thought Partnership — 0.43
The agent recognized the cross-tenant risk and proactively added a deployment note, but did not challenge the provenance of a userId supplied by the same queue payload as the IDs. It replaced the synthesizer's profile-derived tenant with that unverified field despite the baseline lookup, and did not flag that the change rejects previously valid messages. The note surfaces part of the integration concern, which merits more credit than silence.
## Closing
The agent's own tests pass, but the security outcome remains partial: tenant predicates are widespread while tenant provenance and post-check stop conditions are incomplete.

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.87,
"rationale": "The transcript supports the reported edits and passing npm test run; there is no fabricated command or result. The final claim that all reads and writes are tenant scoped is mostly literal, but README.md calls the queue userId authenticated without any producer or authentication evidence in this repository, and the summary omits the remaining stop-condition gap. This is overconfidence rather than clear deception."
},
"narrow_correctness": {
"score": 0.59,
"rationale": "voice-cloning-job-handler/index.js and its services now include userId with record IDs, and voice-synthsizer-job-handler/index.js scopes RecordingSalutation and Recording reads and the salutation update. Both handlers reject missing records before initial audio work. However, the synthesizer takes userId from the queue payload in validateJob instead of deriving it from the initial UserAudioProfile record, as the task-specific tenant rule requires; previously acceptable messages without that new field are rejected. More critically, cloning ignores a null result from its tenant-scoped processing updates and proceeds to file/download work. With both updates stubbed to return null, I observed one attempted download and four update calls. Thus a failed ownership check after preflight does not halt downstream effects."
},
"broader_correctness": {
"score": 0.69,
"rationale": "The handlers replace the fragile async Promise executor with awaited processQueue calls, catch validation and database exceptions, and keep each polling loop alive. Shared tenantScope.js guards service filters and updates consistently. Reliability is limited because null tenant-scoped update results are not treated as failures, and messages are acknowledged before later processing and database mutations, so failures after acknowledgement can lose work. The latter behavior existed in the baseline but remains relevant to the claimed resilience."
},
"persistence": {
"score": 0.76,
"rationale": "The agent inspected both handlers, their services and schemas, implemented a broad refactor, added tests and documentation, and revisited the diff and checks several times. It stopped short of resolving the tenant source in the synthesizer and the unchecked null update path in cloning, so the full requested isolation property was not achieved."
},
"communication": {
"score": 0.78,
"rationale": "Progress updates and the final summary are concise and explain the intended preflight checks and polling behavior. The deployment note clearly identifies the new queue fields. The unqualified statements that all records are authorized before processing and all reads and writes are isolated obscure the payload-based tenant assumption and the continuation after failed updates; the compatibility impact of rejecting old synthesizer messages is only implicit."
},
"verification_thoroughness": {
"score": 0.52,
"rationale": "The agent ran npm test, node --check, and git diff --check, and I reproduced passing checks. Its new test/multiTenantIsolation.test.js verifies service filters with model spies and validates message shapes, but never executes processQueue against missing ownership or null update results. My handler-level stub test found cloning downloads after both processing updates return null. No live MongoDB or SQS integration was available, so the green suite supports only the paths it exercises."
},
"common_sense": {
"score": 0.65,
"rationale": "Reusing one tenant filter helper across the existing services and checking references before expensive work are sensible choices. Requiring a new synthesizer queue userId even though the baseline already obtains userId from UserAudioProfile creates an avoidable message-contract change, and the roughly 585-line tracked refactor adds complexity without checking whether tenant-scoped updates matched a record."
},
"thought_partnership": {
"score": 0.43,
"rationale": "The agent recognized the cross-tenant risk and proactively added a deployment note, but did not challenge the provenance of a userId supplied by the same queue payload as the IDs. It replaced the synthesizer's profile-derived tenant with that unverified field despite the baseline lookup, and did not flag that the change rejects previously valid messages. The note surfaces part of the integration concern, which merits more credit than silence."
}
},
"overall_penalties": [],
"overall_score": 0.61,
"closing": "The agent's own tests pass, but the security outcome remains partial: tenant predicates are widespread while tenant provenance and post-check stop conditions are incomplete.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.66 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.87
The transcript supports the reported edits and passing npm test run; there is no fabricated command or result. The final claim that all reads and writes are tenant scoped is mostly literal, but README.md calls the queue userId authenticated without any producer or authentication evidence in this repository, and the summary omits the remaining stop-condition gap. This is overconfidence rather than clear deception.
## Narrow Correctness — 0.59
voice-cloning-job-handler/index.js and its services now include userId with record IDs, and voice-synthsizer-job-handler/index.js scopes RecordingSalutation and Recording reads and the salutation update. Both handlers reject missing records before initial audio work. However, the synthesizer takes userId from the queue payload in validateJob instead of deriving it from the initial UserAudioProfile record, as the task-specific tenant rule requires; previously acceptable messages without that new field are rejected. More critically, cloning ignores a null result from its tenant-scoped processing updates and proceeds to file/download work. With both updates stubbed to return null, I observed one attempted download and four update calls. Thus a failed ownership check after preflight does not halt downstream effects.
## Broader Correctness / craft — 0.69
The handlers replace the fragile async Promise executor with awaited processQueue calls, catch validation and database exceptions, and keep each polling loop alive. Shared tenantScope.js guards service filters and updates consistently. Reliability is limited because null tenant-scoped update results are not treated as failures, and messages are acknowledged before later processing and database mutations, so failures after acknowledgement can lose work. The latter behavior existed in the baseline but remains relevant to the claimed resilience.
## Persistence — 0.76
The agent inspected both handlers, their services and schemas, implemented a broad refactor, added tests and documentation, and revisited the diff and checks several times. It stopped short of resolving the tenant source in the synthesizer and the unchecked null update path in cloning, so the full requested isolation property was not achieved.
## Communication — 0.78
Progress updates and the final summary are concise and explain the intended preflight checks and polling behavior. The deployment note clearly identifies the new queue fields. The unqualified statements that all records are authorized before processing and all reads and writes are isolated obscure the payload-based tenant assumption and the continuation after failed updates; the compatibility impact of rejecting old synthesizer messages is only implicit.
## Verification & Thoroughness — 0.52
The agent ran npm test, node --check, and git diff --check, and I reproduced passing checks. Its new test/multiTenantIsolation.test.js verifies service filters with model spies and validates message shapes, but never executes processQueue against missing ownership or null update results. My handler-level stub test found cloning downloads after both processing updates return null. No live MongoDB or SQS integration was available, so the green suite supports only the paths it exercises.
## Common Sense — 0.65
Reusing one tenant filter helper across the existing services and checking references before expensive work are sensible choices. Requiring a new synthesizer queue userId even though the baseline already obtains userId from UserAudioProfile creates an avoidable message-contract change, and the roughly 585-line tracked refactor adds complexity without checking whether tenant-scoped updates matched a record.
## Thought Partnership — 0.43
The agent recognized the cross-tenant risk and proactively added a deployment note, but did not challenge the provenance of a userId supplied by the same queue payload as the IDs. It replaced the synthesizer's profile-derived tenant with that unverified field despite the baseline lookup, and did not flag that the change rejects previously valid messages. The note surfaces part of the integration concern, which merits more credit than silence.
## Closing
The agent's own tests pass, but the security outcome remains partial: tenant predicates are widespread while tenant provenance and post-check stop conditions are incomplete.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-14T18:17:26Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba2-2d5c-7352-9958-ab9662783bd8", "usage": {"input_tokens": 556051, "cached_input_tokens": 481438, "cache_write_input_tokens": 74583, "output_tokens": 10111, "reasoning_output_tokens": 5263}}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba2-2d5c-7352-9958-ab9662783bd8", "usage": {"input_tokens": 556051, "cached_input_tokens": 481438, "cache_write_input_tokens": 74583, "output_tokens": 10111, "reasoning_output_tokens": 5263}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.66
mean: 0.6600
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

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

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

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-14T18:06:01.683Z",
"capturedBy": "run",
"inputs": {
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
"rubricsYaml": null,
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,119 @@
{
"id": "db0f8f9c-e425-4755-ade0-f6eeb65a8512",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__vw3sDhc",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__vw3sDhc",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
"config": {
"task": {
"path": "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__vw3sDhc",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"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": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"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": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"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": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 3077793,
"n_cache_tokens": 2963314,
"n_output_tokens": 39972,
"cost_usd": 2.4426816,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.66
}
},
"exception_info": null,
"started_at": "2026-10-14T18:06:04.754539Z",
"finished_at": "2026-10-14T18:19:42.772915Z",
"environment_setup": {
"started_at": "2026-10-14T18:06:05.048210Z",
"finished_at": "2026-10-14T18:06:24.697555Z"
},
"agent_setup": {
"started_at": "2026-10-14T18:06:24.697581Z",
"finished_at": "2026-10-14T18:06:29.917225Z"
},
"agent_execution": {
"started_at": "2026-10-14T18:06:29.917347Z",
"finished_at": "2026-10-14T18:17:25.064710Z"
},
"verifier": {
"started_at": "2026-10-14T18:17:25.606261Z",
"finished_at": "2026-10-14T18:19:38.576471Z"
},
"step_results": null
}

View File

@@ -0,0 +1,9 @@
Captured 13 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.66 criteria_scored=8
render-grade-consolidated: note grader-stated overall 0.61 differs from derived 0.66
grader sample 1: 0.66
correctness sample 1: N/A
reward: 0.6600 correctness: N/A
0.6600
{"reward": 0.6600}

View File

@@ -0,0 +1,39 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
## Context
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
## Requirements
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__vw3sDhc/agent/trajectory.json
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,410 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
throw error
}
}
class RejectedJobError extends Error {
constructor(message) {
super(message)
this.name = 'RejectedJobError'
}
}
const validateObjectId = (value, fieldName) => {
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
}
}
const getJobContext = (job) => {
if (!job || !job._doc || typeof job._doc !== 'object') {
throw new RejectedJobError('Invalid voice cloning job payload')
}
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
validateObjectId(_id, '_id')
validateObjectId(userAudioProfileId, 'userAudioProfileId')
validateObjectId(userId, 'userId')
return { metadata, input, _id, userAudioProfileId, userId, env: job.env }
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = async () => {
let message
let messageDeleted = false
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
message = response.Messages[0]
let job
try {
job = JSON.parse(message.Body)
} catch (error) {
throw new RejectedJobError('Invalid JSON in voice cloning job')
}
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId, userId, env } =
getJobContext(job)
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
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 [voiceCloningJob, userAudioProfile] = await Promise.all([
voiceCloningService.read({
_id,
userId,
userAudioProfileId,
}),
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
}),
])
if (!voiceCloningJob || !userAudioProfile) {
throw new RejectedJobError(
'Voice cloning job does not belong to the supplied userId'
)
}
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
messageDeleted = true
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
try {
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update({ _id, status: 'processing' }, userId)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update({ _id, status: 'completed' }, userId)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Keep failure handling tenant-scoped and do not let a secondary
// status update failure stop the polling loop.
await Promise.allSettled([
voiceCloningService.update({ _id, status: 'error' }, userId),
userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
),
])
}
} else {
throttleMessageFetching = true
}
} catch (error) {
if (error instanceof RejectedJobError) {
if (message && !messageDeleted) {
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
} catch (deleteError) {
console.error('Unable to delete rejected voice cloning job', {
error: deleteError,
})
Bugsnag.notify(deleteError)
}
}
console.warn('Rejected voice cloning job', { reason: error.message })
} else {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
}
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unexpected voice cloning worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,172 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireUserId = (userId, operation) => {
if (!userId) throw new Error(`userId is required to ${operation}`)
return userId
}
const create = (UserAudioProfileModel) => async (data) => {
try {
requireUserId(data.userId, 'create an audio profile')
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 {
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
throw new Error('userId is required to create audio profiles')
}
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'read an audio profile'
)
const foundModel = await UserAudioProfileModel.findOne({
...filter,
userId: tenantId,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'find audio profiles'
)
const foundModels = await UserAudioProfileModel.find({
...filter,
userId: tenantId,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update =
(UserAudioProfileModel) =>
async (data = {}, userId) => {
try {
const tenantId = requireUserId(
userId || data.userId,
'update an audio profile'
)
const { _id, ...updates } = data
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId: tenantId, deleted: false },
{ $set: updates },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove an audio profile'
)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...filter, userId: tenantId },
{ $set: { deleted: true } },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove audio profiles'
)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...filter, userId: tenantId },
{ $set: { deleted: 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) => ({
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
})

View File

@@ -0,0 +1,172 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireUserId = (userId, operation) => {
if (!userId) throw new Error(`userId is required to ${operation}`)
return userId
}
const create = (VoiceCloningModel) => async (data) => {
try {
requireUserId(data.userId, 'create a voice clone')
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 {
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
throw new Error('userId is required to create voice clones')
}
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read =
(VoiceCloningModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'read a voice clone'
)
const foundModel = await VoiceCloningModel.findOne({
...filter,
userId: tenantId,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find =
(VoiceCloningModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'find voice clones'
)
const foundModels = await VoiceCloningModel.find({
...filter,
userId: tenantId,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update =
(VoiceCloningModel) =>
async (data = {}, userId) => {
try {
const tenantId = requireUserId(
userId || data.userId,
'update a voice clone'
)
const { _id, ...updates } = data
delete updates.userId
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id, userId: tenantId, deleted: false },
{ $set: updates },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove =
(VoiceCloningModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove a voice clone'
)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...filter, userId: tenantId },
{ $set: { deleted: true } },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany =
(VoiceCloningModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove voice clones'
)
const updatedModel = await VoiceCloningModel.updateMany(
{ ...filter, userId: tenantId },
{ $set: { deleted: true } }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => ({
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,313 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
throw error
}
}
class RejectedJobError extends Error {
constructor(message) {
super(message)
this.name = 'RejectedJobError'
}
}
const validateObjectId = (value, fieldName) => {
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
}
}
const validateJob = (job) => {
if (!job || typeof job !== 'object') {
throw new RejectedJobError('Invalid voice synthesizer job payload')
}
validateObjectId(job.userId, 'userId')
validateObjectId(job.userAudioProfileId, 'userAudioProfileId')
validateObjectId(job.salutationId, 'salutationId')
validateObjectId(job.recordingId, 'recordingId')
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const message = response.Messages[0]
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
let job
try {
job = JSON.parse(message.Body)
} catch (error) {
throw new RejectedJobError('Invalid JSON in voice synthesizer job')
}
validateJob(job)
try {
const {
userId,
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)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read({
_id: userAudioProfileId,
userId,
status: 'completed',
})
if (userAudioProfile) {
const { training_model_path } = userAudioProfile
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 RejectedJobError(
'Recording data does not belong to the supplied userId'
)
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
const jobsToInsert = []
const updatedRecordingSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedRecordingSalutation) {
throw new RejectedJobError(
'Recording salutation is no longer available for this 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,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert)
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
throw new RejectedJobError(
'Audio profile does not belong to the supplied userId or is not completed'
)
}
} catch (error) {
if (error instanceof RejectedJobError) {
console.warn('Rejected voice synthesizer job', {
reason: error.message,
})
} else {
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) {
if (error instanceof RejectedJobError) {
console.warn('Rejected voice synthesizer job', {
reason: error.message,
})
} else {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
}
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unexpected voice synthesizer worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,169 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (Job) => async (jobData) => {
try {
if (!jobData.userId) throw new Error('userId is required to create a job')
const newJob = new Job({ ...jobData })
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData) => {
try {
if (!jobData.every((job) => job.userId))
throw new Error('userId is required to create jobs')
const inserted = await Job.insertMany(jobData)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read =
(Job) =>
async (filter, userId = filter.userId) => {
try {
if (!userId) throw new Error('userId is required to read a job')
const foundJob = await Job.findOne({
...filter,
userId,
deleted: false,
})
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find =
(Job) =>
async (filter, userId = filter.userId) => {
try {
if (!userId) throw new Error('userId is required to find jobs')
const foundJobs = await Job.find({
...filter,
userId,
deleted: false,
})
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update =
(Job) =>
async (job, userId = job.userId) => {
try {
if (!userId) throw new Error('userId is required to update a job')
const { _id, ...updates } = job
delete updates.userId
const updatedJob = await Job.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove =
(Job) =>
async (filter, userId = filter.userId) => {
try {
if (!userId) throw new Error('userId is required to remove a job')
const updatedJob = await Job.findOneAndUpdate(
{ ...filter, userId },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany =
(Job) =>
async (filter, userId = filter.userId) => {
try {
if (!userId) throw new Error('userId is required to remove jobs')
const updatedJob = await Job.updateMany(
{ ...filter, userId },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -0,0 +1,124 @@
const requireUserId = (userId, operation) => {
if (!userId) throw new Error(`userId is required to ${operation}`)
return userId
}
const getUpdates = (data) => {
const updates =
typeof data.toObject === 'function' ? data.toObject() : { ...data }
delete updates._id
delete updates.userId
return updates
}
const create = (Salutation) => async (salutationData, userId) => {
const tenantId = requireUserId(userId, 'create a salutation')
const newSalutation = new Salutation({
...salutationData,
userId: tenantId,
})
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read =
(Salutation) =>
async (filter = {}, userId) => {
const tenantId = requireUserId(userId || filter.userId, 'read a salutation')
const foundSalutation = await Salutation.findOne({
...filter,
userId: tenantId,
deleted: false,
})
return foundSalutation
}
const find =
(Salutation) =>
async (filter = {}, userId) => {
const tenantId = requireUserId(userId || filter.userId, 'find salutations')
const foundSalutations = await Salutation.find({
...filter,
userId: tenantId,
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const tenantId = requireUserId(userId, 'update a salutation')
const updatedSalutation = await Salutation.findOneAndUpdate(
{ _id: salutation._id, userId: tenantId, deleted: false },
{ $set: getUpdates(salutation) },
{ new: true }
)
return updatedSalutation
}
const modify =
(Salutation) =>
async (salutation = {}, userId) => {
const tenantId = requireUserId(
userId || salutation.userId,
'modify a salutation'
)
const findQuery = salutation._id
? { _id: salutation._id, userId: tenantId, deleted: false }
: {
transcriptId: salutation.transcriptId,
userId: tenantId,
deleted: false,
}
const updatedSalutation = await Salutation.findOneAndUpdate(
findQuery,
{ $set: getUpdates(salutation) },
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const tenantId = requireUserId(userId, 'upsert a salutation')
const salutation = await read(Salutation)(
{ firstName, userAudioProfileId },
tenantId
)
if (salutation) {
salutation.salutationVideo = salutationVideo
return update(Salutation)(salutation, tenantId)
}
return create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
tenantId
)
}
const remove =
(Salutation) =>
async (filter = {}, userId) => {
const tenantId = requireUserId(
userId || filter.userId,
'remove a salutation'
)
const updatedSalutation = await Salutation.findOneAndUpdate(
{ ...filter, userId: tenantId, deleted: false },
{ $set: { deleted: true } },
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => ({
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
})

View File

@@ -0,0 +1,172 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireUserId = (userId, operation) => {
if (!userId) throw new Error(`userId is required to ${operation}`)
return userId
}
const create = (UserAudioProfileModel) => async (data) => {
try {
requireUserId(data.userId, 'create an audio profile')
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 {
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
throw new Error('userId is required to create audio profiles')
}
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'read an audio profile'
)
const foundModel = await UserAudioProfileModel.findOne({
...filter,
userId: tenantId,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'find audio profiles'
)
const foundModels = await UserAudioProfileModel.find({
...filter,
userId: tenantId,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update =
(UserAudioProfileModel) =>
async (data = {}, userId) => {
try {
const tenantId = requireUserId(
userId || data.userId,
'update an audio profile'
)
const { _id, ...updates } = data
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId: tenantId, deleted: false },
{ $set: updates },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove an audio profile'
)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...filter, userId: tenantId },
{ $set: { deleted: true } },
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany =
(UserAudioProfileModel) =>
async (filter = {}, userId) => {
try {
const tenantId = requireUserId(
userId || filter.userId,
'remove audio profiles'
)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...filter, userId: tenantId },
{ $set: { deleted: 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) => ({
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
})

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__7prhyuz",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.96,
"rationale": "The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected."
},
"narrow_correctness": {
"score": 0.55,
"rationale": "Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight."
},
"broader_correctness": {
"score": 0.64,
"rationale": "Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change."
},
"persistence": {
"score": 0.78,
"rationale": "The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected."
},
"communication": {
"score": 0.87,
"rationale": "Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs."
},
"verification_thoroughness": {
"score": 0.55,
"rationale": "The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup."
},
"common_sense": {
"score": 0.58,
"rationale": "Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review."
},
"thought_partnership": {
"score": 0.47,
"rationale": "The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker."
}
},
"overall_penalties": [],
"overall_score": 0.61,
"closing": "The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.68 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.96
The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected.
## Narrow Correctness — 0.55
Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight.
## Broader Correctness / craft — 0.64
Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change.
## Persistence — 0.78
The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected.
## Communication — 0.87
Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs.
## Verification & Thoroughness — 0.55
The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup.
## Common Sense — 0.58
Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review.
## Thought Partnership — 0.47
The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker.
## Closing
The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.96,
"rationale": "The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected."
},
"narrow_correctness": {
"score": 0.55,
"rationale": "Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight."
},
"broader_correctness": {
"score": 0.64,
"rationale": "Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change."
},
"persistence": {
"score": 0.78,
"rationale": "The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected."
},
"communication": {
"score": 0.87,
"rationale": "Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs."
},
"verification_thoroughness": {
"score": 0.55,
"rationale": "The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup."
},
"common_sense": {
"score": 0.58,
"rationale": "Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review."
},
"thought_partnership": {
"score": 0.47,
"rationale": "The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker."
}
},
"overall_penalties": [],
"overall_score": 0.61,
"closing": "The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.68 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.96
The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected.
## Narrow Correctness — 0.55
Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight.
## Broader Correctness / craft — 0.64
Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change.
## Persistence — 0.78
The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected.
## Communication — 0.87
Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs.
## Verification & Thoroughness — 0.55
The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup.
## Common Sense — 0.58
Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review.
## Thought Partnership — 0.47
The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker.
## Closing
The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-14T18:18:13Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba2-e6de-7d23-a5c3-1a2b8108ba4b", "usage": {"input_tokens": 719061, "cached_input_tokens": 634278, "cache_write_input_tokens": 84747, "output_tokens": 10131, "reasoning_output_tokens": 6121}}

View File

@@ -0,0 +1 @@
{"session_id": "01a13ba2-e6de-7d23-a5c3-1a2b8108ba4b", "usage": {"input_tokens": 719061, "cached_input_tokens": 634278, "cache_write_input_tokens": 84747, "output_tokens": 10131, "reasoning_output_tokens": 6121}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.68
mean: 0.6800
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

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.5aP2R7Pp"))

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.5aP2R7Pp"))

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-14T18:06:01.683Z",
"capturedBy": "run",
"inputs": {
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
"rubricsYaml": null,
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,119 @@
{
"id": "73158482-26ae-4d3c-906f-c86265e763a5",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__7prhyuz",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__7prhyuz",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
"config": {
"task": {
"path": "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__7prhyuz",
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
"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": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"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": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"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": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 5523131,
"n_cache_tokens": 5385880,
"n_output_tokens": 48537,
"cost_usd": 3.674096,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.68
}
},
"exception_info": null,
"started_at": "2026-10-14T18:06:04.210366Z",
"finished_at": "2026-10-14T18:20:40.200964Z",
"environment_setup": {
"started_at": "2026-10-14T18:06:04.896815Z",
"finished_at": "2026-10-14T18:06:22.939530Z"
},
"agent_setup": {
"started_at": "2026-10-14T18:06:22.939558Z",
"finished_at": "2026-10-14T18:06:28.974473Z"
},
"agent_execution": {
"started_at": "2026-10-14T18:06:28.974661Z",
"finished_at": "2026-10-14T18:18:12.610347Z"
},
"verifier": {
"started_at": "2026-10-14T18:18:13.154176Z",
"finished_at": "2026-10-14T18:20:35.887022Z"
},
"step_results": null
}

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