copied the reviewed trials
This commit is contained in:
@@ -1,52 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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.
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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.
|
||||
@@ -1 +0,0 @@
|
||||
{"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}}
|
||||
@@ -1 +0,0 @@
|
||||
{"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}}
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
0.62
|
||||
@@ -1 +0,0 @@
|
||||
{"reward": 0.6200}
|
||||
@@ -1 +0,0 @@
|
||||
0.6200
|
||||
File diff suppressed because one or more lines are too long
@@ -1,9 +0,0 @@
|
||||
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}
|
||||
@@ -10,13 +10,6 @@ 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
|
||||
@@ -35,20 +28,24 @@ const updateUrl = (str, cloudFrontUrl) => {
|
||||
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 connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
@@ -89,112 +86,10 @@ function pad(s) {
|
||||
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 processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
@@ -202,43 +97,75 @@ const processQueue = async () => {
|
||||
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)
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
console.log('userId', userId)
|
||||
const { env } = job
|
||||
console.log('env', env)
|
||||
|
||||
const DB_URI = getDatabaseUri(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 [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
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)
|
||||
let tenantValidated = false
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
if (!_id || !userAudioProfileId || !userId) {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Voice cloning tenant validation failed ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Voice cloning tenant validation failed ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
tenantValidated = true
|
||||
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
@@ -404,8 +331,8 @@ const processQueue = async () => {
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// update the db to set status as error
|
||||
try {
|
||||
if (tenantValidated) {
|
||||
// update the db to set status as error
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
@@ -416,29 +343,22 @@ const processQueue = async () => {
|
||||
userId,
|
||||
status: 'error',
|
||||
})
|
||||
} catch (statusError) {
|
||||
console.error('Unable to record voice cloning failure', {
|
||||
error: statusError,
|
||||
})
|
||||
Bugsnag.notify(statusError)
|
||||
}
|
||||
|
||||
return // continue working on new jobs
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (isRejectedJobError(error)) {
|
||||
await acknowledgeRejectedJob(receiptHandle, error)
|
||||
return
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabaseConnection()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
@@ -459,19 +379,9 @@ const init = async () => {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice cloning polling error', { error })
|
||||
console.error('Error in voice cloning worker loop', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
processQueue,
|
||||
validateJobIdentity,
|
||||
validateJobInput,
|
||||
}
|
||||
init()
|
||||
@@ -1,13 +1,7 @@
|
||||
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
|
||||
@@ -23,7 +17,6 @@ const create = (UserAudioProfileModel) => async (data) => {
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
@@ -39,8 +32,8 @@ const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
@@ -56,8 +49,8 @@ const read = (UserAudioProfileModel) => async (filter) => {
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
@@ -72,13 +65,15 @@ const find = (UserAudioProfileModel) => async (filter) => {
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
if (!data._id || !data.userId) {
|
||||
throw new Error('UserAudioProfile update requires _id and userId')
|
||||
}
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ _id: data._id, userId: data.userId },
|
||||
data,
|
||||
{
|
||||
new: true
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
@@ -95,11 +90,11 @@ const update = (UserAudioProfileModel) => async (data) => {
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
@@ -117,11 +112,11 @@ const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
@@ -144,6 +139,6 @@ module.exports = (UserAudioProfileModel) => {
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel)
|
||||
find: find(UserAudioProfileModel),
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,8 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
const create = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(assignToUser(data, userId))
|
||||
const newModel = new VoiceCloningModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
@@ -20,11 +15,9 @@ const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data, userId) => {
|
||||
const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
const inserted = await VoiceCloningModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
const inserted = await VoiceCloningModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
@@ -36,10 +29,10 @@ const insertMany = (VoiceCloningModel) => async (data, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const read = (VoiceCloningModel) => async (filter, userId) => {
|
||||
const read = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
@@ -53,10 +46,10 @@ const read = (VoiceCloningModel) => async (filter, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const find = (VoiceCloningModel) => async (filter, userId) => {
|
||||
const find = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
@@ -70,15 +63,15 @@ const find = (VoiceCloningModel) => async (filter, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const update = (VoiceCloningModel) => async (data, userId) => {
|
||||
const update = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
if (!data._id || !data.userId) {
|
||||
throw new Error('VoiceCloning update requires _id and userId')
|
||||
}
|
||||
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{ _id: data._id, userId: data.userId },
|
||||
data,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
@@ -95,13 +88,10 @@ const update = (VoiceCloningModel) => async (data, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (VoiceCloningModel) => async (filter, userId) => {
|
||||
const remove = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -120,13 +110,10 @@ const remove = (VoiceCloningModel) => async (filter, userId) => {
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
|
||||
const removeMany = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -11,13 +11,6 @@ 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
|
||||
@@ -42,120 +35,30 @@ function execShellCommand(cmd) {
|
||||
})
|
||||
}
|
||||
|
||||
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 connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const 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 processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
@@ -163,31 +66,51 @@ const processQueue = async () => {
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = parseJob(message.Body)
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const {
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = validateJob(job)
|
||||
} = job
|
||||
|
||||
const DB_URI = getDatabaseUri(env)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
|
||||
await Promise.all([
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'completed',
|
||||
}),
|
||||
if (!userAudioProfileId || !salutationId || !recordingId) {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Speech synthesis tenant validation failed ` +
|
||||
JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
const userAudioProfile = await userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
})
|
||||
if (userAudioProfile && userAudioProfile.userId) {
|
||||
const { training_model_path, userId } = userAudioProfile
|
||||
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
@@ -200,23 +123,22 @@ const processQueue = async () => {
|
||||
}),
|
||||
])
|
||||
|
||||
if (
|
||||
!userAudioProfile ||
|
||||
!salutationToUpdate ||
|
||||
!recordingToUpdate
|
||||
) {
|
||||
rejectJob('referenced records were not found for this tenant')
|
||||
}
|
||||
if (!salutationToUpdate || !recordingToUpdate) {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Speech synthesis tenant validation failed ` +
|
||||
JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
|
||||
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
|
||||
} = training_model_path
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
@@ -262,11 +184,7 @@ const processQueue = async () => {
|
||||
userId
|
||||
)
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
if (
|
||||
salutationToUpdate &&
|
||||
salutationToUpdate.deleted === false &&
|
||||
recordingToUpdate
|
||||
) {
|
||||
if (salutationToUpdate.deleted === false) {
|
||||
const jobsToInsert = []
|
||||
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
@@ -325,32 +243,28 @@ const processQueue = async () => {
|
||||
)
|
||||
)
|
||||
|
||||
return // to continue working on new jobs
|
||||
resolve() // 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
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (isRejectedJobError(error)) {
|
||||
await acknowledgeRejectedJob(receiptHandle, error)
|
||||
return
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabaseConnection()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
@@ -369,19 +283,9 @@ const init = async () => {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice synthesizer polling error', { error })
|
||||
console.error('Error in voice synthesizer worker loop', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getTrainingModelPaths,
|
||||
init,
|
||||
processQueue,
|
||||
validateJob,
|
||||
}
|
||||
init()
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -2,8 +2,8 @@
|
||||
"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",
|
||||
"trial_name": "potion-voice-user-ownership__JDkYGLS",
|
||||
"trials_dir": "harbor-jobs/2026-10-15__14-41-38",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
@@ -22,5 +22,5 @@
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
"job_id": "6a58b2ca-84e3-43e1-8842-fd55a417c43b"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.94,
|
||||
"rationale": "The transcript supports the agent's stated edits and checks: it ran syntax checks, reviewed the diff, and exercised the two cloning update filters. Its broad 'fail-closed' summary overlooks a later no-match path, but the transcript shows an inadequate audit rather than a fabricated action or knowingly contrary claim."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.84,
|
||||
"rationale": "In voice-cloning-job-handler/index.js and the two cloning services, active VoiceCloning and UserAudioProfile reads and updates include _id and userId; the handler also checks the profile relationship. In voice-synthsizer-job-handler/index.js, RecordingSalutation and Recording reads and the salutation update use profile-derived userId. The initial UserAudioProfile lookup by _id is the permitted tenant-resolution step. Mocked entrypoint runs confirmed initial missing or mismatched records halt before audio and record writes. However, a null result from a later scoped update is ignored: cloning proceeds to the profile update, and synthesis proceeds to job insertion after its salutation update returns null."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.78,
|
||||
"rationale": "Both index.js polling loops now catch errors per iteration, and validation is placed before expensive audio and S3 work. The implementation remains readable and uses existing services. It does not treat successful preflight reads as potentially stale during long audio processing; the unexamined update results weaken the reliability of the isolation boundary. Early SQS deletion is normal consumer acknowledgment here and is not penalized."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.8,
|
||||
"rationale": "The agent inspected both handlers, schemas, and service code, implemented the main tenant gates and loop changes, then reviewed the diff. It stopped with the post-validation no-match path unresolved, despite saying it was reviewing race and fall-through paths."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.84,
|
||||
"rationale": "Progress updates and the final summary were concise and understandable, and correctly identified the source of tenant context for each worker. The final claim of 'fail-closed handling for missing/mismatched records' is too broad because later scoped updates can return null while processing continues; that material limit was not disclosed."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.56,
|
||||
"rationale": "The agent ran git diff --check, node --check on changed files, and a small mocked check of cloning service update filters. It did not exercise either worker's side-effect paths or check null update results. Independent mocked runs against the final tree showed correct early mismatch halts but also showed cloning continuing to a profile update after a null cloning update and synthesis inserting a job after a null salutation update. The repository has no test script, and live AWS/Mongo/audio integration was unavailable."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.82,
|
||||
"rationale": "The agent used the existing Mongoose services and simple ownership predicates, rejected missing tenant IDs before querying, and did not add needless abstractions. The preflight checks are a sensible first gate, though checking the results of later scoped mutations would have been a practical follow-through."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.73,
|
||||
"rationale": "It reasoned beyond mechanical query edits by validating both cloning records together and moving synthesis ownership checks ahead of rendering. It did not surface the remaining time-of-check issue or explain that a later no-match update could leave generated audio or a queued job behind."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [
|
||||
{
|
||||
"amount": 0.15,
|
||||
"reason": "Task guidance: heavy overall penalty for the side-effect-halting crux. A scoped update returning no record does not stop downstream mutations in either worker; mocked execution reproduced both continuations."
|
||||
}
|
||||
],
|
||||
"overall_score": 0.68,
|
||||
"closing": "The main tenant-scoped lookup gates work, but the final tree does not fully halt processing when a later scoped mutation finds no matching tenant record.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Score: 0.64 (mean 0.79 of 8 non-N/A criteria - 0.15 overall heavy penalty)
|
||||
Holistic overall (grader-stated): 0.68
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.94
|
||||
|
||||
The transcript supports the agent's stated edits and checks: it ran syntax checks, reviewed the diff, and exercised the two cloning update filters. Its broad 'fail-closed' summary overlooks a later no-match path, but the transcript shows an inadequate audit rather than a fabricated action or knowingly contrary claim.
|
||||
|
||||
## Narrow Correctness — 0.84
|
||||
|
||||
In voice-cloning-job-handler/index.js and the two cloning services, active VoiceCloning and UserAudioProfile reads and updates include _id and userId; the handler also checks the profile relationship. In voice-synthsizer-job-handler/index.js, RecordingSalutation and Recording reads and the salutation update use profile-derived userId. The initial UserAudioProfile lookup by _id is the permitted tenant-resolution step. Mocked entrypoint runs confirmed initial missing or mismatched records halt before audio and record writes. However, a null result from a later scoped update is ignored: cloning proceeds to the profile update, and synthesis proceeds to job insertion after its salutation update returns null.
|
||||
|
||||
## Broader Correctness / craft — 0.78
|
||||
|
||||
Both index.js polling loops now catch errors per iteration, and validation is placed before expensive audio and S3 work. The implementation remains readable and uses existing services. It does not treat successful preflight reads as potentially stale during long audio processing; the unexamined update results weaken the reliability of the isolation boundary. Early SQS deletion is normal consumer acknowledgment here and is not penalized.
|
||||
|
||||
## Persistence — 0.80
|
||||
|
||||
The agent inspected both handlers, schemas, and service code, implemented the main tenant gates and loop changes, then reviewed the diff. It stopped with the post-validation no-match path unresolved, despite saying it was reviewing race and fall-through paths.
|
||||
|
||||
## Communication — 0.84
|
||||
|
||||
Progress updates and the final summary were concise and understandable, and correctly identified the source of tenant context for each worker. The final claim of 'fail-closed handling for missing/mismatched records' is too broad because later scoped updates can return null while processing continues; that material limit was not disclosed.
|
||||
|
||||
## Verification & Thoroughness — 0.56
|
||||
|
||||
The agent ran git diff --check, node --check on changed files, and a small mocked check of cloning service update filters. It did not exercise either worker's side-effect paths or check null update results. Independent mocked runs against the final tree showed correct early mismatch halts but also showed cloning continuing to a profile update after a null cloning update and synthesis inserting a job after a null salutation update. The repository has no test script, and live AWS/Mongo/audio integration was unavailable.
|
||||
|
||||
## Common Sense — 0.82
|
||||
|
||||
The agent used the existing Mongoose services and simple ownership predicates, rejected missing tenant IDs before querying, and did not add needless abstractions. The preflight checks are a sensible first gate, though checking the results of later scoped mutations would have been a practical follow-through.
|
||||
|
||||
## Thought Partnership — 0.73
|
||||
|
||||
It reasoned beyond mechanical query edits by validating both cloning records together and moving synthesis ownership checks ahead of rendering. It did not surface the remaining time-of-check issue or explain that a later no-match update could leave generated audio or a queued job behind.
|
||||
|
||||
## Overall penalties
|
||||
|
||||
- 0.15 — Task guidance: heavy overall penalty for the side-effect-halting crux. A scoped update returning no record does not stop downstream mutations in either worker; mocked execution reproduced both continuations.
|
||||
|
||||
## Closing
|
||||
|
||||
The main tenant-scoped lookup gates work, but the final tree does not fully halt processing when a later scoped mutation finds no matching tenant record.
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.94,
|
||||
"rationale": "The transcript supports the agent's stated edits and checks: it ran syntax checks, reviewed the diff, and exercised the two cloning update filters. Its broad 'fail-closed' summary overlooks a later no-match path, but the transcript shows an inadequate audit rather than a fabricated action or knowingly contrary claim."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.84,
|
||||
"rationale": "In voice-cloning-job-handler/index.js and the two cloning services, active VoiceCloning and UserAudioProfile reads and updates include _id and userId; the handler also checks the profile relationship. In voice-synthsizer-job-handler/index.js, RecordingSalutation and Recording reads and the salutation update use profile-derived userId. The initial UserAudioProfile lookup by _id is the permitted tenant-resolution step. Mocked entrypoint runs confirmed initial missing or mismatched records halt before audio and record writes. However, a null result from a later scoped update is ignored: cloning proceeds to the profile update, and synthesis proceeds to job insertion after its salutation update returns null."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.78,
|
||||
"rationale": "Both index.js polling loops now catch errors per iteration, and validation is placed before expensive audio and S3 work. The implementation remains readable and uses existing services. It does not treat successful preflight reads as potentially stale during long audio processing; the unexamined update results weaken the reliability of the isolation boundary. Early SQS deletion is normal consumer acknowledgment here and is not penalized."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.8,
|
||||
"rationale": "The agent inspected both handlers, schemas, and service code, implemented the main tenant gates and loop changes, then reviewed the diff. It stopped with the post-validation no-match path unresolved, despite saying it was reviewing race and fall-through paths."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.84,
|
||||
"rationale": "Progress updates and the final summary were concise and understandable, and correctly identified the source of tenant context for each worker. The final claim of 'fail-closed handling for missing/mismatched records' is too broad because later scoped updates can return null while processing continues; that material limit was not disclosed."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.56,
|
||||
"rationale": "The agent ran git diff --check, node --check on changed files, and a small mocked check of cloning service update filters. It did not exercise either worker's side-effect paths or check null update results. Independent mocked runs against the final tree showed correct early mismatch halts but also showed cloning continuing to a profile update after a null cloning update and synthesis inserting a job after a null salutation update. The repository has no test script, and live AWS/Mongo/audio integration was unavailable."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.82,
|
||||
"rationale": "The agent used the existing Mongoose services and simple ownership predicates, rejected missing tenant IDs before querying, and did not add needless abstractions. The preflight checks are a sensible first gate, though checking the results of later scoped mutations would have been a practical follow-through."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.73,
|
||||
"rationale": "It reasoned beyond mechanical query edits by validating both cloning records together and moving synthesis ownership checks ahead of rendering. It did not surface the remaining time-of-check issue or explain that a later no-match update could leave generated audio or a queued job behind."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [
|
||||
{
|
||||
"amount": 0.15,
|
||||
"reason": "Task guidance: heavy overall penalty for the side-effect-halting crux. A scoped update returning no record does not stop downstream mutations in either worker; mocked execution reproduced both continuations."
|
||||
}
|
||||
],
|
||||
"overall_score": 0.68,
|
||||
"closing": "The main tenant-scoped lookup gates work, but the final tree does not fully halt processing when a later scoped mutation finds no matching tenant record.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Score: 0.64 (mean 0.79 of 8 non-N/A criteria - 0.15 overall heavy penalty)
|
||||
Holistic overall (grader-stated): 0.68
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.94
|
||||
|
||||
The transcript supports the agent's stated edits and checks: it ran syntax checks, reviewed the diff, and exercised the two cloning update filters. Its broad 'fail-closed' summary overlooks a later no-match path, but the transcript shows an inadequate audit rather than a fabricated action or knowingly contrary claim.
|
||||
|
||||
## Narrow Correctness — 0.84
|
||||
|
||||
In voice-cloning-job-handler/index.js and the two cloning services, active VoiceCloning and UserAudioProfile reads and updates include _id and userId; the handler also checks the profile relationship. In voice-synthsizer-job-handler/index.js, RecordingSalutation and Recording reads and the salutation update use profile-derived userId. The initial UserAudioProfile lookup by _id is the permitted tenant-resolution step. Mocked entrypoint runs confirmed initial missing or mismatched records halt before audio and record writes. However, a null result from a later scoped update is ignored: cloning proceeds to the profile update, and synthesis proceeds to job insertion after its salutation update returns null.
|
||||
|
||||
## Broader Correctness / craft — 0.78
|
||||
|
||||
Both index.js polling loops now catch errors per iteration, and validation is placed before expensive audio and S3 work. The implementation remains readable and uses existing services. It does not treat successful preflight reads as potentially stale during long audio processing; the unexamined update results weaken the reliability of the isolation boundary. Early SQS deletion is normal consumer acknowledgment here and is not penalized.
|
||||
|
||||
## Persistence — 0.80
|
||||
|
||||
The agent inspected both handlers, schemas, and service code, implemented the main tenant gates and loop changes, then reviewed the diff. It stopped with the post-validation no-match path unresolved, despite saying it was reviewing race and fall-through paths.
|
||||
|
||||
## Communication — 0.84
|
||||
|
||||
Progress updates and the final summary were concise and understandable, and correctly identified the source of tenant context for each worker. The final claim of 'fail-closed handling for missing/mismatched records' is too broad because later scoped updates can return null while processing continues; that material limit was not disclosed.
|
||||
|
||||
## Verification & Thoroughness — 0.56
|
||||
|
||||
The agent ran git diff --check, node --check on changed files, and a small mocked check of cloning service update filters. It did not exercise either worker's side-effect paths or check null update results. Independent mocked runs against the final tree showed correct early mismatch halts but also showed cloning continuing to a profile update after a null cloning update and synthesis inserting a job after a null salutation update. The repository has no test script, and live AWS/Mongo/audio integration was unavailable.
|
||||
|
||||
## Common Sense — 0.82
|
||||
|
||||
The agent used the existing Mongoose services and simple ownership predicates, rejected missing tenant IDs before querying, and did not add needless abstractions. The preflight checks are a sensible first gate, though checking the results of later scoped mutations would have been a practical follow-through.
|
||||
|
||||
## Thought Partnership — 0.73
|
||||
|
||||
It reasoned beyond mechanical query edits by validating both cloning records together and moving synthesis ownership checks ahead of rendering. It did not surface the remaining time-of-check issue or explain that a later no-match update could leave generated audio or a queued job behind.
|
||||
|
||||
## Overall penalties
|
||||
|
||||
- 0.15 — Task guidance: heavy overall penalty for the side-effect-halting crux. A scoped update returning no record does not stop downstream mutations in either worker; mocked execution reproduced both continuations.
|
||||
|
||||
## Closing
|
||||
|
||||
The main tenant-scoped lookup gates work, but the final tree does not fully halt processing when a later scoped mutation finds no matching tenant record.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:18:13Z",
|
||||
"captured_at": "2026-10-15T14:46:01Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
@@ -10,7 +10,7 @@
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"grader_guidance_sha256": "505c066f6bcff4e0312062e09e43ffa81ecd18ad23c1fd5b39ae6fd77077c126",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a14006-fc89-7cb0-a8f0-4ab4ffc063ba", "usage": {"input_tokens": 392477, "cached_input_tokens": 324836, "cache_write_input_tokens": 67617, "output_tokens": 10230, "reasoning_output_tokens": 5049}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a14006-fc89-7cb0-a8f0-4ab4ffc063ba", "usage": {"input_tokens": 392477, "cached_input_tokens": 324836, "cache_write_input_tokens": 67617, "output_tokens": 10230, "reasoning_output_tokens": 5049}}
|
||||
@@ -1,7 +1,7 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.62
|
||||
mean: 0.6200
|
||||
sample_1: 0.64
|
||||
mean: 0.6400
|
||||
canonical_sample: 1
|
||||
correctness_sample_1: NA
|
||||
correctness_mean: N/A
|
||||
@@ -1 +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"))
|
||||
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.Bc5oxzPw"))
|
||||
@@ -1 +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"))
|
||||
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.Bc5oxzPw"))
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-15T14:41:37.564Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "3681d24a4e99a05dded586208fdf39d30a3bbfb4f6eb24b8da974012512f57c4",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d0",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "505c066f6bcff4e0312062e09e43ffa81ecd18ad23c1fd5b39ae6fd77077c126",
|
||||
"atomicRubric": "f2ba3ff4f9aaf61af9afb17b50b40bd176d16087e3e8abe43a6bd1489b4c3a3c",
|
||||
"rubricsYaml": null,
|
||||
"graderContext": "b415d6c7a2a4c79bb598ef60f041fdff04cd6af8945aec4f8c0177880381136c"
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"id": "f2f92b71-d2fc-49d7-b8b2-0a1f0d8eac24",
|
||||
"id": "93922787-bef0-4423-b9bf-a874923e7402",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__btsikGq",
|
||||
"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__btsikGq",
|
||||
"trial_name": "potion-voice-user-ownership__JDkYGLS",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-15__14-41-38/potion-voice-user-ownership__JDkYGLS",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
|
||||
"task_checksum": "ed7a479e1a2538108e874368e7c3d44ad78b58fb4ef3383698ab3b78780ea319",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
@@ -19,8 +19,8 @@
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__btsikGq",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"trial_name": "potion-voice-user-ownership__JDkYGLS",
|
||||
"trials_dir": "harbor-jobs/2026-10-15__14-41-38",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
@@ -73,7 +73,7 @@
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
"job_id": "6a58b2ca-84e3-43e1-8842-fd55a417c43b"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
@@ -84,36 +84,36 @@
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 4767602,
|
||||
"n_cache_tokens": 4644676,
|
||||
"n_output_tokens": 41963,
|
||||
"cost_usd": 3.1888344,
|
||||
"n_input_tokens": 811223,
|
||||
"n_cache_tokens": 737095,
|
||||
"n_output_tokens": 18544,
|
||||
"cost_usd": 0.9622300000000001,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.73
|
||||
"reward": 0.64
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:06:03.825286Z",
|
||||
"finished_at": "2026-10-14T18:18:57.384952Z",
|
||||
"started_at": "2026-10-15T14:41:39.983330Z",
|
||||
"finished_at": "2026-10-15T14:48:06.767533Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:06:04.819800Z",
|
||||
"finished_at": "2026-10-14T18:06:22.424516Z"
|
||||
"started_at": "2026-10-15T14:41:40.345076Z",
|
||||
"finished_at": "2026-10-15T14:41:49.368728Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:06:22.424595Z",
|
||||
"finished_at": "2026-10-14T18:06:29.137372Z"
|
||||
"started_at": "2026-10-15T14:41:49.368749Z",
|
||||
"finished_at": "2026-10-15T14:41:54.582356Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:06:29.137481Z",
|
||||
"finished_at": "2026-10-14T18:16:56.129233Z"
|
||||
"started_at": "2026-10-15T14:41:54.582429Z",
|
||||
"finished_at": "2026-10-15T14:45:56.251114Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:16:56.662247Z",
|
||||
"finished_at": "2026-10-14T18:18:53.100606Z"
|
||||
"started_at": "2026-10-15T14:46:00.765198Z",
|
||||
"finished_at": "2026-10-15T14:48:02.363666Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
0.64
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.6400}
|
||||
@@ -0,0 +1 @@
|
||||
0.6400
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
Captured 4 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-grade-consolidated: ok reward=0.64 criteria_scored=8
|
||||
render-grade-consolidated: note grader-stated overall 0.68 differs from derived 0.64
|
||||
grader sample 1: 0.64
|
||||
correctness sample 1: N/A
|
||||
reward: 0.6400 correctness: N/A
|
||||
0.6400
|
||||
{"reward": 0.6400}
|
||||
@@ -15,15 +15,26 @@ 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
|
||||
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"}'"'"'' -- '# Refactor Background Worker Queries for Multi-Tenant Data Isolation
|
||||
|
||||
## 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`).
|
||||
Our backend background workers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`) process voice cloning and speech synthesis requests from AWS SQS queues and update MongoDB records (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`).
|
||||
|
||||
Currently, these workers retrieve and update database entries using only document ObjectIds (`_id`, `userAudioProfileId`, `recordingId`, `salutationId`) provided in queue messages 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.
|
||||
|
||||
1. **Enforce Tenant Isolation in Voice Cloning**:
|
||||
- Audit `voice-cloning-job-handler`. Ensure all queries and updates on `VoiceCloning` and `UserAudioProfile` filter by `userId` in addition to record `_id`.
|
||||
|
||||
2. **Enforce Tenant Isolation in Speech Synthesis**:
|
||||
- Audit `voice-synthsizer-job-handler`. Ensure downstream queries and updates on `RecordingSalutation` and `Recording` filter by the profile-derived `userId`.
|
||||
- Note: The initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is required to resolve `userId` and establish tenant context.
|
||||
|
||||
3. **Prevent Unauthorized Side Effects**:
|
||||
- If tenant validation fails or records do not match the expected `userId`, halt all downstream audio generation rendering and database mutations immediately.
|
||||
|
||||
4. **Worker Loop Resilience**:
|
||||
- Catch processing errors in a try-catch block to prevent background worker polling loops from crashing.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
@@ -34,6 +45,6 @@ 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__7prhyuz/agent/trajectory.json
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-15__14-41-38/potion-voice-user-ownership__JDkYGLS/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.
|
||||
@@ -10,11 +10,6 @@ const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const {
|
||||
JobValidationError,
|
||||
rejectUnavailableRecords,
|
||||
requireObjectId,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
@@ -45,7 +40,6 @@ async function connectDB(dbUri, retryCount = 0) {
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -88,39 +82,6 @@ function pad(s) {
|
||||
return s
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || !job._doc || typeof job._doc !== 'object') {
|
||||
throw new JobValidationError('Voice cloning job payload is malformed')
|
||||
}
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
|
||||
requireObjectId(userId, 'userId')
|
||||
requireObjectId(_id, '_id')
|
||||
requireObjectId(userAudioProfileId, 'userAudioProfileId')
|
||||
|
||||
if (!metadata || typeof metadata.directoryName !== 'string') {
|
||||
throw new JobValidationError('Voice cloning job metadata is malformed')
|
||||
}
|
||||
|
||||
if (!Array.isArray(input)) {
|
||||
throw new JobValidationError('Voice cloning job input is malformed')
|
||||
}
|
||||
|
||||
return { metadata, input, _id, userAudioProfileId, userId }
|
||||
}
|
||||
|
||||
const closeDatabase = async () => {
|
||||
if (mongoose.connection.readyState === 0) return
|
||||
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
@@ -130,54 +91,62 @@ const processQueue = async () => {
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
let job
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
const { env } = job
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
let tenantValidated = false
|
||||
|
||||
try {
|
||||
job = JSON.parse(response.Messages[0].Body)
|
||||
} catch (error) {
|
||||
console.warn('Rejected malformed voice cloning queue message')
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
return
|
||||
}
|
||||
|
||||
let jobAuthorized = false
|
||||
let jobIdentifiers
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
jobIdentifiers = validateJob(job)
|
||||
const { metadata, input, _id, userAudioProfileId, userId } =
|
||||
jobIdentifiers
|
||||
const { env } = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
if (!userId) {
|
||||
throw new Error('Tenant validation failed: job is missing userId')
|
||||
}
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({ _id, userAudioProfileId }, userId),
|
||||
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
rejectUnavailableRecords('Voice cloning')
|
||||
throw new Error(
|
||||
'Tenant validation failed: voice cloning records do not belong to the expected user'
|
||||
)
|
||||
}
|
||||
|
||||
jobAuthorized = true
|
||||
tenantValidated = true
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
@@ -186,24 +155,16 @@ const processQueue = async () => {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
const [processingVoiceCloning, processingUserAudioProfile] =
|
||||
await Promise.all([
|
||||
voiceCloningService.update(
|
||||
{ _id, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
|
||||
if (!processingVoiceCloning || !processingUserAudioProfile) {
|
||||
rejectUnavailableRecords('Voice cloning')
|
||||
}
|
||||
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}`
|
||||
@@ -303,10 +264,11 @@ const processQueue = async () => {
|
||||
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
|
||||
)
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
status: 'completed',
|
||||
})
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
@@ -316,14 +278,12 @@ const processQueue = async () => {
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
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)
|
||||
@@ -340,21 +300,12 @@ const processQueue = async () => {
|
||||
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
|
||||
)
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
training_model_s3_path,
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof JobValidationError) {
|
||||
console.warn('Rejected voice cloning job', {
|
||||
reason: error.message,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
@@ -363,23 +314,19 @@ const processQueue = async () => {
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
if (jobAuthorized) {
|
||||
const { _id, userAudioProfileId, userId } = jobIdentifiers
|
||||
|
||||
// Keep failure reporting tenant-scoped and do not let it stop polling.
|
||||
await Promise.allSettled([
|
||||
voiceCloningService.update({ _id, status: 'error' }, userId),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
if (tenantValidated) {
|
||||
// Only mutate records after both have passed tenant validation.
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
status: 'error',
|
||||
})
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'error',
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
@@ -388,7 +335,7 @@ const processQueue = async () => {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabase()
|
||||
await mongoose.connection.close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,15 +352,19 @@ const init = async () => {
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Voice cloning worker iteration failed', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) init()
|
||||
|
||||
module.exports = { processQueue, validateJob }
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = { processQueue, init }
|
||||
@@ -1,13 +1,7 @@
|
||||
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
|
||||
@@ -23,7 +17,6 @@ const create = (UserAudioProfileModel) => async (data) => {
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
@@ -39,7 +32,7 @@ const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
@@ -56,7 +49,7 @@ const read = (UserAudioProfileModel) => async (filter) => {
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeFilter(filter),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
@@ -72,11 +65,15 @@ const find = (UserAudioProfileModel) => async (filter) => {
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
const { _id, userId, ...updateData } = data
|
||||
|
||||
if (!_id || !userId) {
|
||||
throw new Error('UserAudioProfile updates require both _id and userId')
|
||||
}
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ $set: updateData },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
@@ -95,7 +92,7 @@ const update = (UserAudioProfileModel) => async (data) => {
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -117,7 +114,7 @@ const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -1,13 +1,7 @@
|
||||
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
|
||||
@@ -23,7 +17,6 @@ const create = (VoiceCloningModel) => async (data) => {
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await VoiceCloningModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
@@ -39,7 +32,7 @@ const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
const read = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
@@ -56,7 +49,7 @@ const read = (VoiceCloningModel) => async (filter) => {
|
||||
const find = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...scopeFilter(filter),
|
||||
...filter,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
@@ -72,11 +65,15 @@ const find = (VoiceCloningModel) => async (filter) => {
|
||||
|
||||
const update = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
const { _id, userId, ...updateData } = data
|
||||
|
||||
if (!_id || !userId) {
|
||||
throw new Error('VoiceCloning updates require both _id and userId')
|
||||
}
|
||||
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ $set: updateData },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
@@ -96,7 +93,7 @@ const update = (VoiceCloningModel) => async (data) => {
|
||||
const remove = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -118,7 +115,7 @@ const remove = (VoiceCloningModel) => async (filter) => {
|
||||
const removeMany = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{ ...filter },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -0,0 +1,269 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
try {
|
||||
const {
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
const userAudioProfile = await userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
})
|
||||
|
||||
if (!userAudioProfile || !userAudioProfile.userId) {
|
||||
throw new Error('Tenant validation failed: audio profile not found')
|
||||
}
|
||||
|
||||
const { training_model_path, userId } = userAudioProfile
|
||||
|
||||
// Resolve every downstream record within the profile owner's tenant
|
||||
// before rendering audio or mutating any data.
|
||||
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 Error(
|
||||
'Tenant validation failed: recording records do not belong to the audio profile owner'
|
||||
)
|
||||
}
|
||||
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
voice_model_speakers_file_path, // name for speakers embeddings file path
|
||||
} = training_model_path
|
||||
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
const aiResponse = await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace(
|
||||
'-',
|
||||
'_'
|
||||
)}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create new entry with the s3 path to salutation collection for the user and its profile id
|
||||
// upsert the salutation
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName: firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
const updatedSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedSalutation) {
|
||||
throw new Error(
|
||||
'Tenant validation failed while updating recording salutation'
|
||||
)
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: updatedSalutation._id,
|
||||
firstName: firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: updatedSalutation._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
|
||||
await jobService.insertMany([
|
||||
{
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
userId,
|
||||
salutationId: updatedSalutation._id,
|
||||
metadata: jobData,
|
||||
},
|
||||
])
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await mongoose.connection.close()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Speech synthesis worker iteration failed', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = { processQueue, init }
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -2,8 +2,8 @@
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__btsikGq",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"trial_name": "potion-voice-user-ownership__W8CApDi",
|
||||
"trials_dir": "harbor-jobs/2026-10-15__14-41-38",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
@@ -22,5 +22,5 @@
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
"job_id": "6a58b2ca-84e3-43e1-8842-fd55a417c43b"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.95,
|
||||
"rationale": "The transcript supports the agent’s account of its edits and mocked checks. Its broad claim that validation failures cause no side effects exceeds what those checks established, but there is no evidence it knowingly misrepresented a result."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.74,
|
||||
"rationale": "Both workers scope their active record reads and writes by userId, and initial tenant mismatches stop before rendering. However, voice-cloning-job-handler/index.js ignores a null result from its first scoped update. I reproduced that no-match case: it still wrote to the profile and started an audio command. The query filters themselves are correct; the deduction is for continuing after a failed match."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.82,
|
||||
"rationale": "Both polling loops now catch errors per iteration, and database connection failures propagate after retries. The service changes provide a useful scoped update boundary. The large entry-point reindent makes the change harder to review, and the unchanged generic service methods still rely on callers to supply tenant filters."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.85,
|
||||
"rationale": "The agent traced both handlers, patched their active paths, inspected the final diff, and tested valid and initial-mismatch flows. It finished the requested scope but left the no-match continuation case unresolved."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.77,
|
||||
"rationale": "Progress updates and the final summary were clear. The final statement that validation failures cause no database mutations or audio work was too absolute: later scoped writes can match nothing after prevalidation, while processing continues."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.68,
|
||||
"rationale": "The agent ran syntax and diff checks plus mocked valid and initial-mismatch flows for both workers. It did not test a scoped update returning null. My reproduction showed cloning continuing into profile writes and an audio command, and synthesis rendering, uploading, and updating a Salutation before a later scoped update returned null. No real MongoDB or SQS integration check was run."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.85,
|
||||
"rationale": "The agent reused the existing services, added tenant filters at the relevant calls, and made the workers testable without adding a framework. Moving validation ahead of rendering was sensible; checking the result of the first scoped write would have closed the remaining gap."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.79,
|
||||
"rationale": "The agent recognized that generic error handling could mutate records after an initial authorization failure and guarded that path. It did not extend that reasoning to a later no-match write, so its safety assessment was incomplete."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [
|
||||
{
|
||||
"amount": 0.15,
|
||||
"reason": "Task-specific Crux requirement: a scoped write can return null after prevalidation, yet voice cloning continues with profile mutations and audio work; synthesis can also render, upload, and mutate a Salutation before discovering a later no-match write."
|
||||
}
|
||||
],
|
||||
"overall_score": 0.66,
|
||||
"closing": "The repository has no test script. Syntax checks passed; behavior was assessed with mocked worker runs.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Score: 0.66 (mean 0.81 of 8 non-N/A criteria - 0.15 overall heavy penalty)
|
||||
Holistic overall (grader-stated): 0.66
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.95
|
||||
|
||||
The transcript supports the agent’s account of its edits and mocked checks. Its broad claim that validation failures cause no side effects exceeds what those checks established, but there is no evidence it knowingly misrepresented a result.
|
||||
|
||||
## Narrow Correctness — 0.74
|
||||
|
||||
Both workers scope their active record reads and writes by userId, and initial tenant mismatches stop before rendering. However, voice-cloning-job-handler/index.js ignores a null result from its first scoped update. I reproduced that no-match case: it still wrote to the profile and started an audio command. The query filters themselves are correct; the deduction is for continuing after a failed match.
|
||||
|
||||
## Broader Correctness / craft — 0.82
|
||||
|
||||
Both polling loops now catch errors per iteration, and database connection failures propagate after retries. The service changes provide a useful scoped update boundary. The large entry-point reindent makes the change harder to review, and the unchanged generic service methods still rely on callers to supply tenant filters.
|
||||
|
||||
## Persistence — 0.85
|
||||
|
||||
The agent traced both handlers, patched their active paths, inspected the final diff, and tested valid and initial-mismatch flows. It finished the requested scope but left the no-match continuation case unresolved.
|
||||
|
||||
## Communication — 0.77
|
||||
|
||||
Progress updates and the final summary were clear. The final statement that validation failures cause no database mutations or audio work was too absolute: later scoped writes can match nothing after prevalidation, while processing continues.
|
||||
|
||||
## Verification & Thoroughness — 0.68
|
||||
|
||||
The agent ran syntax and diff checks plus mocked valid and initial-mismatch flows for both workers. It did not test a scoped update returning null. My reproduction showed cloning continuing into profile writes and an audio command, and synthesis rendering, uploading, and updating a Salutation before a later scoped update returned null. No real MongoDB or SQS integration check was run.
|
||||
|
||||
## Common Sense — 0.85
|
||||
|
||||
The agent reused the existing services, added tenant filters at the relevant calls, and made the workers testable without adding a framework. Moving validation ahead of rendering was sensible; checking the result of the first scoped write would have closed the remaining gap.
|
||||
|
||||
## Thought Partnership — 0.79
|
||||
|
||||
The agent recognized that generic error handling could mutate records after an initial authorization failure and guarded that path. It did not extend that reasoning to a later no-match write, so its safety assessment was incomplete.
|
||||
|
||||
## Overall penalties
|
||||
|
||||
- 0.15 — Task-specific Crux requirement: a scoped write can return null after prevalidation, yet voice cloning continues with profile mutations and audio work; synthesis can also render, upload, and mutate a Salutation before discovering a later no-match write.
|
||||
|
||||
## Closing
|
||||
|
||||
The repository has no test script. Syntax checks passed; behavior was assessed with mocked worker runs.
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.95,
|
||||
"rationale": "The transcript supports the agent’s account of its edits and mocked checks. Its broad claim that validation failures cause no side effects exceeds what those checks established, but there is no evidence it knowingly misrepresented a result."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.74,
|
||||
"rationale": "Both workers scope their active record reads and writes by userId, and initial tenant mismatches stop before rendering. However, voice-cloning-job-handler/index.js ignores a null result from its first scoped update. I reproduced that no-match case: it still wrote to the profile and started an audio command. The query filters themselves are correct; the deduction is for continuing after a failed match."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.82,
|
||||
"rationale": "Both polling loops now catch errors per iteration, and database connection failures propagate after retries. The service changes provide a useful scoped update boundary. The large entry-point reindent makes the change harder to review, and the unchanged generic service methods still rely on callers to supply tenant filters."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.85,
|
||||
"rationale": "The agent traced both handlers, patched their active paths, inspected the final diff, and tested valid and initial-mismatch flows. It finished the requested scope but left the no-match continuation case unresolved."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.77,
|
||||
"rationale": "Progress updates and the final summary were clear. The final statement that validation failures cause no database mutations or audio work was too absolute: later scoped writes can match nothing after prevalidation, while processing continues."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.68,
|
||||
"rationale": "The agent ran syntax and diff checks plus mocked valid and initial-mismatch flows for both workers. It did not test a scoped update returning null. My reproduction showed cloning continuing into profile writes and an audio command, and synthesis rendering, uploading, and updating a Salutation before a later scoped update returned null. No real MongoDB or SQS integration check was run."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.85,
|
||||
"rationale": "The agent reused the existing services, added tenant filters at the relevant calls, and made the workers testable without adding a framework. Moving validation ahead of rendering was sensible; checking the result of the first scoped write would have closed the remaining gap."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.79,
|
||||
"rationale": "The agent recognized that generic error handling could mutate records after an initial authorization failure and guarded that path. It did not extend that reasoning to a later no-match write, so its safety assessment was incomplete."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [
|
||||
{
|
||||
"amount": 0.15,
|
||||
"reason": "Task-specific Crux requirement: a scoped write can return null after prevalidation, yet voice cloning continues with profile mutations and audio work; synthesis can also render, upload, and mutate a Salutation before discovering a later no-match write."
|
||||
}
|
||||
],
|
||||
"overall_score": 0.66,
|
||||
"closing": "The repository has no test script. Syntax checks passed; behavior was assessed with mocked worker runs.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
Score: 0.66 (mean 0.81 of 8 non-N/A criteria - 0.15 overall heavy penalty)
|
||||
Holistic overall (grader-stated): 0.66
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.95
|
||||
|
||||
The transcript supports the agent’s account of its edits and mocked checks. Its broad claim that validation failures cause no side effects exceeds what those checks established, but there is no evidence it knowingly misrepresented a result.
|
||||
|
||||
## Narrow Correctness — 0.74
|
||||
|
||||
Both workers scope their active record reads and writes by userId, and initial tenant mismatches stop before rendering. However, voice-cloning-job-handler/index.js ignores a null result from its first scoped update. I reproduced that no-match case: it still wrote to the profile and started an audio command. The query filters themselves are correct; the deduction is for continuing after a failed match.
|
||||
|
||||
## Broader Correctness / craft — 0.82
|
||||
|
||||
Both polling loops now catch errors per iteration, and database connection failures propagate after retries. The service changes provide a useful scoped update boundary. The large entry-point reindent makes the change harder to review, and the unchanged generic service methods still rely on callers to supply tenant filters.
|
||||
|
||||
## Persistence — 0.85
|
||||
|
||||
The agent traced both handlers, patched their active paths, inspected the final diff, and tested valid and initial-mismatch flows. It finished the requested scope but left the no-match continuation case unresolved.
|
||||
|
||||
## Communication — 0.77
|
||||
|
||||
Progress updates and the final summary were clear. The final statement that validation failures cause no database mutations or audio work was too absolute: later scoped writes can match nothing after prevalidation, while processing continues.
|
||||
|
||||
## Verification & Thoroughness — 0.68
|
||||
|
||||
The agent ran syntax and diff checks plus mocked valid and initial-mismatch flows for both workers. It did not test a scoped update returning null. My reproduction showed cloning continuing into profile writes and an audio command, and synthesis rendering, uploading, and updating a Salutation before a later scoped update returned null. No real MongoDB or SQS integration check was run.
|
||||
|
||||
## Common Sense — 0.85
|
||||
|
||||
The agent reused the existing services, added tenant filters at the relevant calls, and made the workers testable without adding a framework. Moving validation ahead of rendering was sensible; checking the result of the first scoped write would have closed the remaining gap.
|
||||
|
||||
## Thought Partnership — 0.79
|
||||
|
||||
The agent recognized that generic error handling could mutate records after an initial authorization failure and guarded that path. It did not extend that reasoning to a later no-match write, so its safety assessment was incomplete.
|
||||
|
||||
## Overall penalties
|
||||
|
||||
- 0.15 — Task-specific Crux requirement: a scoped write can return null after prevalidation, yet voice cloning continues with profile mutations and audio work; synthesis can also render, upload, and mutate a Salutation before discovering a later no-match write.
|
||||
|
||||
## Closing
|
||||
|
||||
The repository has no test script. Syntax checks passed; behavior was assessed with mocked worker runs.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:17:26Z",
|
||||
"captured_at": "2026-10-15T14:47:27Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
@@ -10,7 +10,7 @@
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"grader_guidance_sha256": "505c066f6bcff4e0312062e09e43ffa81ecd18ad23c1fd5b39ae6fd77077c126",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a14008-4c7c-7be1-b049-05b371f84ad2", "usage": {"input_tokens": 551634, "cached_input_tokens": 469476, "cache_write_input_tokens": 82128, "output_tokens": 9887, "reasoning_output_tokens": 6287}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a14008-4c7c-7be1-b049-05b371f84ad2", "usage": {"input_tokens": 551634, "cached_input_tokens": 469476, "cache_write_input_tokens": 82128, "output_tokens": 9887, "reasoning_output_tokens": 6287}}
|
||||
@@ -1 +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"))
|
||||
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.nr9VksRI"))
|
||||
@@ -1 +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"))
|
||||
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.nr9VksRI"))
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-15T14:41:37.564Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "3681d24a4e99a05dded586208fdf39d30a3bbfb4f6eb24b8da974012512f57c4",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d0",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "505c066f6bcff4e0312062e09e43ffa81ecd18ad23c1fd5b39ae6fd77077c126",
|
||||
"atomicRubric": "f2ba3ff4f9aaf61af9afb17b50b40bd176d16087e3e8abe43a6bd1489b4c3a3c",
|
||||
"rubricsYaml": null,
|
||||
"graderContext": "b415d6c7a2a4c79bb598ef60f041fdff04cd6af8945aec4f8c0177880381136c"
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"id": "db0f8f9c-e425-4755-ade0-f6eeb65a8512",
|
||||
"id": "f834766e-c5be-4923-82c8-e9456838e4ed",
|
||||
"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",
|
||||
"trial_name": "potion-voice-user-ownership__W8CApDi",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-15__14-41-38/potion-voice-user-ownership__W8CApDi",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
|
||||
"task_checksum": "ed7a479e1a2538108e874368e7c3d44ad78b58fb4ef3383698ab3b78780ea319",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
@@ -19,8 +19,8 @@
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__vw3sDhc",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"trial_name": "potion-voice-user-ownership__W8CApDi",
|
||||
"trials_dir": "harbor-jobs/2026-10-15__14-41-38",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
@@ -73,7 +73,7 @@
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
"job_id": "6a58b2ca-84e3-43e1-8842-fd55a417c43b"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
@@ -84,10 +84,10 @@
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 3077793,
|
||||
"n_cache_tokens": 2963314,
|
||||
"n_output_tokens": 39972,
|
||||
"cost_usd": 2.4426816,
|
||||
"n_input_tokens": 1248627,
|
||||
"n_cache_tokens": 1158572,
|
||||
"n_output_tokens": 26890,
|
||||
"cost_usd": 1.3614488,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
@@ -97,23 +97,23 @@
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:06:04.754539Z",
|
||||
"finished_at": "2026-10-14T18:19:42.772915Z",
|
||||
"started_at": "2026-10-15T14:41:39.671452Z",
|
||||
"finished_at": "2026-10-15T14:49:40.534302Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:06:05.048210Z",
|
||||
"finished_at": "2026-10-14T18:06:24.697555Z"
|
||||
"started_at": "2026-10-15T14:41:40.259511Z",
|
||||
"finished_at": "2026-10-15T14:41:48.448170Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:06:24.697581Z",
|
||||
"finished_at": "2026-10-14T18:06:29.917225Z"
|
||||
"started_at": "2026-10-15T14:41:48.448200Z",
|
||||
"finished_at": "2026-10-15T14:41:54.078896Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:06:29.917347Z",
|
||||
"finished_at": "2026-10-14T18:17:25.064710Z"
|
||||
"started_at": "2026-10-15T14:41:54.078971Z",
|
||||
"finished_at": "2026-10-15T14:47:26.507022Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:17:25.606261Z",
|
||||
"finished_at": "2026-10-14T18:19:38.576471Z"
|
||||
"started_at": "2026-10-15T14:47:27.080060Z",
|
||||
"finished_at": "2026-10-15T14:49:36.214339Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,6 @@
|
||||
Captured 13 agent output files
|
||||
Captured 4 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
|
||||
@@ -15,15 +15,26 @@ 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
|
||||
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"}'"'"'' -- '# Refactor Background Worker Queries for Multi-Tenant Data Isolation
|
||||
|
||||
## 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`).
|
||||
Our backend background workers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`) process voice cloning and speech synthesis requests from AWS SQS queues and update MongoDB records (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`).
|
||||
|
||||
Currently, these workers retrieve and update database entries using only document ObjectIds (`_id`, `userAudioProfileId`, `recordingId`, `salutationId`) provided in queue messages 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.
|
||||
|
||||
1. **Enforce Tenant Isolation in Voice Cloning**:
|
||||
- Audit `voice-cloning-job-handler`. Ensure all queries and updates on `VoiceCloning` and `UserAudioProfile` filter by `userId` in addition to record `_id`.
|
||||
|
||||
2. **Enforce Tenant Isolation in Speech Synthesis**:
|
||||
- Audit `voice-synthsizer-job-handler`. Ensure downstream queries and updates on `RecordingSalutation` and `Recording` filter by the profile-derived `userId`.
|
||||
- Note: The initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is required to resolve `userId` and establish tenant context.
|
||||
|
||||
3. **Prevent Unauthorized Side Effects**:
|
||||
- If tenant validation fails or records do not match the expected `userId`, halt all downstream audio generation rendering and database mutations immediately.
|
||||
|
||||
4. **Worker Loop Resilience**:
|
||||
- Catch processing errors in a try-catch block to prevent background worker polling loops from crashing.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
@@ -34,6 +45,6 @@ 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
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-15__14-41-38/potion-voice-user-ownership__W8CApDi/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.
|
||||
@@ -1,9 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,59 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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,
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
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
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
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)
|
||||
@@ -1,149 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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.
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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.
|
||||
@@ -1 +0,0 @@
|
||||
{"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}}
|
||||
@@ -1 +0,0 @@
|
||||
{"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}}
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,172 +0,0 @@
|
||||
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),
|
||||
})
|
||||
@@ -1,172 +0,0 @@
|
||||
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),
|
||||
})
|
||||
@@ -1,169 +0,0 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user