atomic regrades
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"job_name": "regrade-reward-0.6200-2WLWKV8-1792003823-25375",
|
||||
"jobs_dir": "harbor-jobs/reward-0.6200-2WLWKV8",
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"agents": [
|
||||
{
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6200-2WLWKV8",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"created_at": "2026-10-14T18:50:25.068322Z",
|
||||
"harbor": {
|
||||
"version": "0.20.0",
|
||||
"is_editable": false
|
||||
},
|
||||
"n_concurrent_trials": 4,
|
||||
"retry": {
|
||||
"max_retries": 0,
|
||||
"exclude_exceptions": [
|
||||
"AgentTimeoutError",
|
||||
"AgentSafetyRefusalError",
|
||||
"VerifierOutputParseError",
|
||||
"RewardFileEmptyError",
|
||||
"ApiUsageLimitError",
|
||||
"VerifierTimeoutError",
|
||||
"AgentAuthenticationError",
|
||||
"RewardFileNotFoundError",
|
||||
"ModelNotFoundError"
|
||||
],
|
||||
"wait_multiplier": 1.0,
|
||||
"min_wait_sec": 1.0,
|
||||
"max_wait_sec": 60.0
|
||||
},
|
||||
"trials": [
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6200-2WLWKV8",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"source": "/logs/artifacts",
|
||||
"destination": "artifacts/logs/artifacts",
|
||||
"type": "directory",
|
||||
"status": "empty",
|
||||
"service": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__JYkhBR5",
|
||||
"trials_dir": "harbor-jobs/reward-0.6200-2WLWKV8/regrade-reward-0.6200-2WLWKV8-1792003823-25375",
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6200-2WLWKV8",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "95e850d3-3355-4b9d-af5c-037d52b420b1"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6200-2WLWKV8",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "dd58e1c7-6d73-454a-8306-c6303356bec5",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__JYkhBR5",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.6200-2WLWKV8/regrade-reward-0.6200-2WLWKV8-1792003823-25375/potion-voice-user-ownership__JYkhBR5",
|
||||
"task_id": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "e7448a852b6cc12f4becc265a689d065e3489e2c023066b3b005927140515027",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__JYkhBR5",
|
||||
"trials_dir": "harbor-jobs/reward-0.6200-2WLWKV8/regrade-reward-0.6200-2WLWKV8-1792003823-25375",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"model_name": null,
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6200-2WLWKV8",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "95e850d3-3355-4b9d-af5c-037d52b420b1"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "replay",
|
||||
"version": "1.0.0",
|
||||
"model_info": null
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": null,
|
||||
"n_cache_tokens": null,
|
||||
"n_output_tokens": null,
|
||||
"cost_usd": null,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.89
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:50:25.387741Z",
|
||||
"finished_at": "2026-10-14T18:52:45.510057Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:50:25.543601Z",
|
||||
"finished_at": "2026-10-14T18:50:29.475587Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:50:29.475637Z",
|
||||
"finished_at": "2026-10-14T18:50:29.475683Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:50:29.475741Z",
|
||||
"finished_at": "2026-10-14T18:50:29.909366Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:50:30.497793Z",
|
||||
"finished_at": "2026-10-14T18:52:41.296790Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,52 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const parseJobMessage = (body) => {
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Queue message body is not valid JSON')
|
||||
}
|
||||
}
|
||||
|
||||
const requireJobObject = (value, fieldName) => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new RejectedJobError(`${fieldName} is required`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireJobObjectId = (value, fieldName) => {
|
||||
const isObjectId = value instanceof mongoose.Types.ObjectId
|
||||
const isObjectIdString =
|
||||
typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value)
|
||||
|
||||
if (!isObjectId && !isObjectIdString) {
|
||||
throw new RejectedJobError(`${fieldName} must be a valid ObjectId`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireJobString = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || value.trim() === '') {
|
||||
throw new RejectedJobError(`${fieldName} is required`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const requireUserId = (userId) => {
|
||||
const isObjectId = userId instanceof mongoose.Types.ObjectId
|
||||
const isObjectIdString =
|
||||
typeof userId === 'string' && /^[a-fA-F0-9]{24}$/.test(userId)
|
||||
|
||||
if (!isObjectId && !isObjectIdString) {
|
||||
throw new TypeError(
|
||||
'A valid userId is required for tenant-scoped database access'
|
||||
)
|
||||
}
|
||||
|
||||
return userId
|
||||
}
|
||||
|
||||
const scopeToUser = (filter, userId) => ({
|
||||
...filter,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const assignToUser = (data, userId) => ({
|
||||
...data,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const withoutTenantIdentity = (data) => {
|
||||
const updates = { ...data }
|
||||
delete updates._id
|
||||
delete updates.userId
|
||||
|
||||
if (Object.keys(updates).some((key) => key.startsWith('$'))) {
|
||||
throw new TypeError('MongoDB update operators are not allowed')
|
||||
}
|
||||
|
||||
return updates
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
assignToUser,
|
||||
requireUserId,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let authorized = false
|
||||
let userId
|
||||
let voiceCloningId
|
||||
let userAudioProfileId
|
||||
let receiptHandle
|
||||
let acknowledged = false
|
||||
|
||||
const acknowledgeMessage = async () => {
|
||||
if (!acknowledged && receiptHandle) {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
acknowledged = true
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (!response.Messages || response.Messages.length === 0) {
|
||||
throttleMessageFetching = true
|
||||
return
|
||||
}
|
||||
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = requireJobObject(parseJobMessage(message.Body), 'job')
|
||||
const jobDocument = requireJobObject(job._doc, 'job._doc')
|
||||
|
||||
userId = requireJobObjectId(jobDocument.userId, 'userId')
|
||||
voiceCloningId = requireJobObjectId(jobDocument._id, '_id')
|
||||
userAudioProfileId = requireJobObjectId(
|
||||
jobDocument.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
)
|
||||
const env = requireJobString(job.env, 'env')
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read(
|
||||
{ _id: voiceCloningId, userAudioProfileId },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job records were not found for the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
authorized = true
|
||||
const metadata = requireJobObject(voiceCloning.metadata, 'metadata')
|
||||
const directoryName = requireJobString(
|
||||
metadata.directoryName,
|
||||
'metadata.directoryName'
|
||||
)
|
||||
const input = voiceCloning.input
|
||||
if (!Array.isArray(input)) {
|
||||
throw new RejectedJobError('input must be an array')
|
||||
}
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
// Keep the existing at-most-once processing behavior once the job and all
|
||||
// tenant-owned records have been validated.
|
||||
await acknowledgeMessage()
|
||||
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
|
||||
const [processingJob, processingProfile] = await Promise.all([
|
||||
voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
])
|
||||
if (!processingJob || !processingProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job records changed before processing'
|
||||
)
|
||||
}
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
await execShellCommand(samplingCommand, logPath)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
await execShellCommand(trainingModelCommand, logPath)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
await execShellCommand(minimizeCloningModelCommand, logPath)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'completed' },
|
||||
userId
|
||||
)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
const keys = Object.keys(training_model_path)
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, training_model_s3_path },
|
||||
userId
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn(`Rejected voice cloning job: ${error.message}`)
|
||||
try {
|
||||
await acknowledgeMessage()
|
||||
} catch (acknowledgementError) {
|
||||
console.error('Unable to acknowledge rejected voice cloning job', {
|
||||
error: acknowledgementError,
|
||||
})
|
||||
Bugsnag.notify(acknowledgementError)
|
||||
}
|
||||
} else {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
|
||||
if (authorized) {
|
||||
const statusUpdates = await Promise.allSettled([
|
||||
voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'error' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, status: 'error' },
|
||||
userId
|
||||
),
|
||||
])
|
||||
statusUpdates
|
||||
.filter(({ status }) => status === 'rejected')
|
||||
.forEach(({ reason }) => Bugsnag.notify(reason))
|
||||
}
|
||||
} finally {
|
||||
if (mongoose.connection.readyState !== 0) {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
connectDB,
|
||||
processQueue,
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await VoiceCloningModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => {
|
||||
return {
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
const {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let receiptHandle
|
||||
let acknowledged = false
|
||||
|
||||
const acknowledgeMessage = async () => {
|
||||
if (!acknowledged && receiptHandle) {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
acknowledged = true
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (!response.Messages || response.Messages.length === 0) {
|
||||
throttleMessageFetching = true
|
||||
return
|
||||
}
|
||||
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = requireJobObject(parseJobMessage(message.Body), 'job')
|
||||
|
||||
const userId = requireJobObjectId(job.userId, 'userId')
|
||||
const userAudioProfileId = requireJobObjectId(
|
||||
job.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
)
|
||||
const salutationId = requireJobObjectId(job.salutationId, 'salutationId')
|
||||
const recordingId = requireJobObjectId(job.recordingId, 'recordingId')
|
||||
const text = requireJobString(job.text, 'text')
|
||||
const firstName = requireJobString(job.firstName, 'firstName')
|
||||
const env = requireJobString(job.env, 'env')
|
||||
const { baseUrlForPotionAi } = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// Authorize every referenced record before voice synthesis or S3 writes.
|
||||
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
|
||||
await Promise.all([
|
||||
userAudioProfileService.read(
|
||||
{ _id: userAudioProfileId, status: 'completed' },
|
||||
userId
|
||||
),
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!userAudioProfile || !salutationToUpdate || !recordingToUpdate) {
|
||||
throw new RejectedJobError(
|
||||
'Synthesizer job records were not found for the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
const trainingModelPath = requireJobObject(
|
||||
userAudioProfile.training_model_path,
|
||||
'training_model_path'
|
||||
)
|
||||
const voiceModelLightPath = requireJobString(
|
||||
trainingModelPath.voice_model_light_path,
|
||||
'training_model_path.voice_model_light_path'
|
||||
)
|
||||
const voiceModelConfigLightPath = requireJobString(
|
||||
trainingModelPath.voice_model_config_light_path,
|
||||
'training_model_path.voice_model_config_light_path'
|
||||
)
|
||||
const voiceModelSpeakersFilePath = requireJobString(
|
||||
trainingModelPath.voice_model_speakers_file_path,
|
||||
'training_model_path.voice_model_speakers_file_path'
|
||||
)
|
||||
|
||||
// Keep the existing at-most-once processing behavior once the job and all
|
||||
// tenant-owned records have been validated.
|
||||
await acknowledgeMessage()
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voiceModelLightPath} --voice_model_config_path ${voiceModelConfigLightPath} --speaker_embeddings_path ${voiceModelSpeakersFilePath} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create or update the per-user cached salutation.
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
const updatedSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedSalutation) {
|
||||
throw new RejectedJobError(
|
||||
'Recording salutation changed before it could be updated'
|
||||
)
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: updatedSalutation._id,
|
||||
firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: updatedSalutation._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
|
||||
await jobService.insertMany(
|
||||
[
|
||||
{
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutationId: updatedSalutation._id,
|
||||
metadata: jobData,
|
||||
},
|
||||
],
|
||||
userId
|
||||
)
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn(`Rejected voice synthesizer job: ${error.message}`)
|
||||
try {
|
||||
await acknowledgeMessage()
|
||||
} catch (acknowledgementError) {
|
||||
console.error('Unable to acknowledge rejected voice synthesizer job', {
|
||||
error: acknowledgementError,
|
||||
})
|
||||
Bugsnag.notify(acknowledgementError)
|
||||
}
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
if (mongoose.connection.readyState !== 0) {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
connectDB,
|
||||
processQueue,
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const newJob = new Job(assignToUser(jobData, userId))
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const inserted = await Job.insertMany(
|
||||
jobData.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const foundJob = await Job.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const foundJobs = await Job.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (Job) => async (job, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(job)
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: job._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedJob = await Job.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (Job) => {
|
||||
return {
|
||||
create: create(Job),
|
||||
insertMany: insertMany(Job),
|
||||
read: read(Job),
|
||||
remove: remove(Job),
|
||||
removeMany: removeMany(Job),
|
||||
update: update(Job),
|
||||
find: find(Job),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const newSalutation = new Salutation(assignToUser(salutationData, userId))
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const updates = withoutTenantIdentity(salutation)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: salutation._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id }
|
||||
: { transcriptId: salutation.transcriptId }
|
||||
const updates = withoutTenantIdentity(salutation)
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(findQuery, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
const salutation = await read(Salutation)(
|
||||
{
|
||||
firstName,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
if (salutation) {
|
||||
return await update(Salutation)(
|
||||
{ _id: salutation._id, salutationVideo },
|
||||
userId
|
||||
)
|
||||
} else {
|
||||
return await create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Salutation) => async (filter, userId) => {
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
module.exports = (Salutation) => {
|
||||
return {
|
||||
create: create(Salutation),
|
||||
read: read(Salutation),
|
||||
remove: remove(Salutation),
|
||||
update: update(Salutation),
|
||||
updateOrCreate: updateOrCreate(Salutation),
|
||||
find: find(Salutation),
|
||||
modify: modify(Salutation),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning worker reads VoiceCloning and UserAudioProfile using record IDs and userId (index.js:122-144). Every later job and profile update passes userId, and the service update filters combine it with _id (index.js:179-188, 284-304, 320-323, 340-350).
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads, and the RecordingSalutation update, filter by _id and userId (index.js:114-123, 193-206). The userId comes from job.userId at line 86 rather than from the initial UserAudioProfile result. The scoped profile read establishes equality when it succeeds, but the specified tenant-resolution path is absent.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesis worker requires job.userId before its profile lookup and passes that value into the lookup (index.js:86, 110-113); it never obtains userId from the returned profile. The base worker obtained userId from the profile. A mocked check confirmed that a message with the baseline fields but no userId is rejected before any profile read.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Both workers check their referenced tenant-scoped records before creating files, generating audio, uploading to S3, or making downstream mutations (cloning index.js:138-150; synthesis index.js:107-130). Independent mocked ownership-failure runs completed with acknowledgment and zero filesystem or database writes.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Both processQueue functions catch parsing, validation, and database failures and guard connection closure in finally blocks (cloning index.js:108-365; synthesis index.js:73-273). Mocked rejected jobs returned normally, allowing the polling loops to continue.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning worker logs rejected jobs and, after authorization, may set the requesting VoiceCloning job to status 'error' through an _id and userId scoped update (index.js:324-354). This is a permitted lifecycle update.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The final transcript message concisely describes tenant-scoped access, authorization before processing, rejected-job handling, and the new queue userId requirement. That requirement exposes the synthesis compatibility defect graded above.
|
||||
|
||||
## Closing
|
||||
|
||||
Syntax and diff checks passed; the repository defines no test script.
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning worker reads VoiceCloning and UserAudioProfile using record IDs and userId (index.js:122-144). Every later job and profile update passes userId, and the service update filters combine it with _id (index.js:179-188, 284-304, 320-323, 340-350).
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads, and the RecordingSalutation update, filter by _id and userId (index.js:114-123, 193-206). The userId comes from job.userId at line 86 rather than from the initial UserAudioProfile result. The scoped profile read establishes equality when it succeeds, but the specified tenant-resolution path is absent.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesis worker requires job.userId before its profile lookup and passes that value into the lookup (index.js:86, 110-113); it never obtains userId from the returned profile. The base worker obtained userId from the profile. A mocked check confirmed that a message with the baseline fields but no userId is rejected before any profile read.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Both workers check their referenced tenant-scoped records before creating files, generating audio, uploading to S3, or making downstream mutations (cloning index.js:138-150; synthesis index.js:107-130). Independent mocked ownership-failure runs completed with acknowledgment and zero filesystem or database writes.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Both processQueue functions catch parsing, validation, and database failures and guard connection closure in finally blocks (cloning index.js:108-365; synthesis index.js:73-273). Mocked rejected jobs returned normally, allowing the polling loops to continue.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning worker logs rejected jobs and, after authorization, may set the requesting VoiceCloning job to status 'error' through an _id and userId scoped update (index.js:324-354). This is a permitted lifecycle update.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The final transcript message concisely describes tenant-scoped access, authorization before processing, rejected-job handling, and the new queue userId requirement. That requirement exposes the synthesis compatibility defect graded above.
|
||||
|
||||
## Closing
|
||||
|
||||
Syntax and diff checks passed; the repository defines no test script.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:50:30Z",
|
||||
"grader_mode": "rubric-trinary",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "rubric-trinary",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "rubric-criteria.md",
|
||||
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
|
||||
"render_grade_file": "render-rubric-grade.py",
|
||||
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc0-7d95-7183-b473-bae45f1777b7", "usage": {"input_tokens": 1030220, "cached_input_tokens": 945570, "cache_write_input_tokens": 84602, "output_tokens": 9944, "reasoning_output_tokens": 3554}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc0-7d95-7183-b473-bae45f1777b7", "usage": {"input_tokens": 1030220, "cached_input_tokens": 945570, "cache_write_input_tokens": 84602, "output_tokens": 9944, "reasoning_output_tokens": 3554}}
|
||||
@@ -0,0 +1,6 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.89
|
||||
mean: 0.8900
|
||||
canonical_sample: 1
|
||||
correctness_mean: (none)
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.hsYShZy9"))
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.hsYShZy9"))
|
||||
@@ -0,0 +1 @@
|
||||
0.89
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.8900}
|
||||
@@ -0,0 +1 @@
|
||||
0.8900
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"form": "trinary",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "cloning-tenant-isolation",
|
||||
"rationale": "The cloning worker reads VoiceCloning and UserAudioProfile using record IDs and userId (index.js:122-144). Every later job and profile update passes userId, and the service update filters combine it with _id (index.js:179-188, 284-304, 320-323, 340-350).",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "synthesis-tenant-isolation-queries-updates",
|
||||
"rationale": "RecordingSalutation and Recording reads, and the RecordingSalutation update, filter by _id and userId (index.js:114-123, 193-206). The userId comes from job.userId at line 86 rather than from the initial UserAudioProfile result. The scoped profile read establishes equality when it succeeds, but the specified tenant-resolution path is absent.",
|
||||
"verdict": "partial"
|
||||
},
|
||||
{
|
||||
"id": "initial-profile-tenant-resolution",
|
||||
"rationale": "The synthesis worker requires job.userId before its profile lookup and passes that value into the lookup (index.js:86, 110-113); it never obtains userId from the returned profile. The base worker obtained userId from the profile. A mocked check confirmed that a message with the baseline fields but no userId is rejected before any profile read.",
|
||||
"verdict": "fail"
|
||||
},
|
||||
{
|
||||
"id": "prevent-unauthorized-side-effects",
|
||||
"rationale": "Both workers check their referenced tenant-scoped records before creating files, generating audio, uploading to S3, or making downstream mutations (cloning index.js:138-150; synthesis index.js:107-130). Independent mocked ownership-failure runs completed with acknowledgment and zero filesystem or database writes.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "worker-loop-crash-prevention",
|
||||
"rationale": "Both processQueue functions catch parsing, validation, and database failures and guard connection closure in finally blocks (cloning index.js:108-365; synthesis index.js:73-273). Mocked rejected jobs returned normally, allowing the polling loops to continue.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "error-status-lifecycle-logging",
|
||||
"rationale": "The cloning worker logs rejected jobs and, after authorization, may set the requesting VoiceCloning job to status 'error' through an _id and userId scoped update (index.js:324-354). This is a permitted lifecycle update.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "refactor-summary-clarity",
|
||||
"rationale": "The final transcript message concisely describes tenant-scoped access, authorization before processing, rejected-job handling, and the new queue userId requirement. That requirement exposes the synthesis compatibility defect graded above.",
|
||||
"verdict": "pass"
|
||||
}
|
||||
],
|
||||
"closing": "Syntax and diff checks passed; the repository defines no test script.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-rubric-grade/2.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"form": "trinary",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "cloning-tenant-isolation",
|
||||
"rationale": "The cloning worker reads VoiceCloning and UserAudioProfile using record IDs and userId (index.js:122-144). Every later job and profile update passes userId, and the service update filters combine it with _id (index.js:179-188, 284-304, 320-323, 340-350).",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "synthesis-tenant-isolation-queries-updates",
|
||||
"rationale": "RecordingSalutation and Recording reads, and the RecordingSalutation update, filter by _id and userId (index.js:114-123, 193-206). The userId comes from job.userId at line 86 rather than from the initial UserAudioProfile result. The scoped profile read establishes equality when it succeeds, but the specified tenant-resolution path is absent.",
|
||||
"verdict": "partial"
|
||||
},
|
||||
{
|
||||
"id": "initial-profile-tenant-resolution",
|
||||
"rationale": "The synthesis worker requires job.userId before its profile lookup and passes that value into the lookup (index.js:86, 110-113); it never obtains userId from the returned profile. The base worker obtained userId from the profile. A mocked check confirmed that a message with the baseline fields but no userId is rejected before any profile read.",
|
||||
"verdict": "fail"
|
||||
},
|
||||
{
|
||||
"id": "prevent-unauthorized-side-effects",
|
||||
"rationale": "Both workers check their referenced tenant-scoped records before creating files, generating audio, uploading to S3, or making downstream mutations (cloning index.js:138-150; synthesis index.js:107-130). Independent mocked ownership-failure runs completed with acknowledgment and zero filesystem or database writes.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "worker-loop-crash-prevention",
|
||||
"rationale": "Both processQueue functions catch parsing, validation, and database failures and guard connection closure in finally blocks (cloning index.js:108-365; synthesis index.js:73-273). Mocked rejected jobs returned normally, allowing the polling loops to continue.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "error-status-lifecycle-logging",
|
||||
"rationale": "The cloning worker logs rejected jobs and, after authorization, may set the requesting VoiceCloning job to status 'error' through an _id and userId scoped update (index.js:324-354). This is a permitted lifecycle update.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "refactor-summary-clarity",
|
||||
"rationale": "The final transcript message concisely describes tenant-scoped access, authorization before processing, rejected-job handling, and the new queue userId requirement. That requirement exposes the synthesis compatibility defect graded above.",
|
||||
"verdict": "pass"
|
||||
}
|
||||
],
|
||||
"closing": "Syntax and diff checks passed; the repository defines no test script.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-rubric-grade/2.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
Captured 9 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-rubric-grade: ok reward=0.89 form=trinary criteria=7 excluded_extra_credit=0 partial_extra_credit=0 total_weight=41
|
||||
grader sample 1: 0.89
|
||||
reward: 0.8900 correctness: (none)
|
||||
0.8900
|
||||
{"reward": 0.8900}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "95e850d3-3355-4b9d-af5c-037d52b420b1",
|
||||
"started_at": "2026-10-14T18:50:24.873223",
|
||||
"updated_at": "2026-10-14T18:52:45.516059",
|
||||
"finished_at": "2026-10-14T18:52:45.516059",
|
||||
"n_total_trials": 1,
|
||||
"stats": {
|
||||
"n_completed_trials": 1,
|
||||
"n_errored_trials": 0,
|
||||
"n_running_trials": 0,
|
||||
"n_pending_trials": 0,
|
||||
"n_cancelled_trials": 0,
|
||||
"n_retries": 0,
|
||||
"evals": {
|
||||
"replay__adhoc": {
|
||||
"n_trials": 1,
|
||||
"n_errors": 0,
|
||||
"metrics": [
|
||||
{
|
||||
"mean": 0.89
|
||||
}
|
||||
],
|
||||
"pass_at_k": {},
|
||||
"reward_stats": {
|
||||
"reward": {
|
||||
"0.89": [
|
||||
"potion-voice-user-ownership__JYkhBR5"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exception_stats": {}
|
||||
}
|
||||
},
|
||||
"n_input_tokens": null,
|
||||
"n_cache_tokens": null,
|
||||
"n_output_tokens": null,
|
||||
"cost_usd": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"job_name": "regrade-reward-0.6600-vw3sDhc-1792004076-26513",
|
||||
"jobs_dir": "harbor-jobs/reward-0.6600-vw3sDhc",
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"agents": [
|
||||
{
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-vw3sDhc",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"created_at": "2026-10-14T18:54:37.462245Z",
|
||||
"harbor": {
|
||||
"version": "0.20.0",
|
||||
"is_editable": false
|
||||
},
|
||||
"n_concurrent_trials": 4,
|
||||
"retry": {
|
||||
"max_retries": 0,
|
||||
"exclude_exceptions": [
|
||||
"RewardFileNotFoundError",
|
||||
"VerifierTimeoutError",
|
||||
"ModelNotFoundError",
|
||||
"VerifierOutputParseError",
|
||||
"ApiUsageLimitError",
|
||||
"RewardFileEmptyError",
|
||||
"AgentAuthenticationError",
|
||||
"AgentSafetyRefusalError",
|
||||
"AgentTimeoutError"
|
||||
],
|
||||
"wait_multiplier": 1.0,
|
||||
"min_wait_sec": 1.0,
|
||||
"max_wait_sec": 60.0
|
||||
},
|
||||
"trials": [
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-vw3sDhc",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"source": "/logs/artifacts",
|
||||
"destination": "artifacts/logs/artifacts",
|
||||
"type": "directory",
|
||||
"status": "empty",
|
||||
"service": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__pqHcH9x",
|
||||
"trials_dir": "harbor-jobs/reward-0.6600-vw3sDhc/regrade-reward-0.6600-vw3sDhc-1792004076-26513",
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-vw3sDhc",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "30ab2ac3-aa1c-4501-bfd4-b9465601df01"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-vw3sDhc",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "8d63e5c1-8d40-493b-8a16-415fb5e151fe",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__pqHcH9x",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.6600-vw3sDhc/regrade-reward-0.6600-vw3sDhc-1792004076-26513/potion-voice-user-ownership__pqHcH9x",
|
||||
"task_id": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "0fd43034bfd4a9e76e1839db319e8a4e177b145d92e059be3014b030a7a14039",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__pqHcH9x",
|
||||
"trials_dir": "harbor-jobs/reward-0.6600-vw3sDhc/regrade-reward-0.6600-vw3sDhc-1792004076-26513",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"model_name": null,
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-vw3sDhc",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "30ab2ac3-aa1c-4501-bfd4-b9465601df01"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "replay",
|
||||
"version": "1.0.0",
|
||||
"model_info": null
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": null,
|
||||
"n_cache_tokens": null,
|
||||
"n_output_tokens": null,
|
||||
"cost_usd": null,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.89
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:54:37.786090Z",
|
||||
"finished_at": "2026-10-14T18:56:58.568565Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:54:37.975538Z",
|
||||
"finished_at": "2026-10-14T18:54:41.549687Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:54:41.549735Z",
|
||||
"finished_at": "2026-10-14T18:54:41.549782Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:54:41.549836Z",
|
||||
"finished_at": "2026-10-14T18:54:41.963647Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:54:42.513568Z",
|
||||
"finished_at": "2026-10-14T18:56:54.322116Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,9 @@
|
||||
# potion-voice
|
||||
Potion's Text-to-Speech Service (multi-speaker baseline model training, voice cloning and speech synthesising)
|
||||
|
||||
## Worker tenant contract
|
||||
|
||||
Every queue message must carry the authenticated tenant's MongoDB `userId`.
|
||||
Voice-cloning messages carry it in `_doc.userId`; voice-synthesizer messages carry
|
||||
it at the top level. Messages with a missing/invalid tenant ID, or references to
|
||||
records outside that tenant, are rejected and acknowledged without processing.
|
||||
@@ -0,0 +1,59 @@
|
||||
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
|
||||
|
||||
const tenantIdRequiredError = () => {
|
||||
const error = new TypeError(
|
||||
'a valid userId is required for tenant-scoped database access'
|
||||
)
|
||||
error.code = 'TENANT_ID_REQUIRED'
|
||||
return error
|
||||
}
|
||||
|
||||
const requireTenantId = (userId) => {
|
||||
const isStringId =
|
||||
typeof userId === 'string' && OBJECT_ID_PATTERN.test(userId)
|
||||
const isObjectId =
|
||||
userId &&
|
||||
typeof userId === 'object' &&
|
||||
(userId._bsontype === 'ObjectID' || userId._bsontype === 'ObjectId') &&
|
||||
OBJECT_ID_PATTERN.test(String(userId))
|
||||
|
||||
if (!isStringId && !isObjectId) {
|
||||
throw tenantIdRequiredError()
|
||||
}
|
||||
|
||||
return userId
|
||||
}
|
||||
|
||||
const scopeFilter = (filter) => {
|
||||
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
||||
throw tenantIdRequiredError()
|
||||
}
|
||||
|
||||
requireTenantId(filter.userId)
|
||||
return { ...filter, userId: filter.userId }
|
||||
}
|
||||
|
||||
const requireTenantData = (data) => {
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||||
throw tenantIdRequiredError()
|
||||
}
|
||||
|
||||
requireTenantId(data.userId)
|
||||
return data
|
||||
}
|
||||
|
||||
const requireTenantDataList = (data) => {
|
||||
if (!Array.isArray(data)) {
|
||||
throw tenantIdRequiredError()
|
||||
}
|
||||
|
||||
data.forEach(requireTenantData)
|
||||
return data
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
requireTenantData,
|
||||
requireTenantDataList,
|
||||
requireTenantId,
|
||||
scopeFilter,
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
|
||||
const VALID_ENVIRONMENTS = new Set(['development', 'staging', 'production'])
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
this.code = 'JOB_REJECTED'
|
||||
}
|
||||
}
|
||||
|
||||
const requireObjectId = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || !OBJECT_ID_PATTERN.test(value)) {
|
||||
throw new RejectedJobError(`${fieldName} must be a valid ObjectId`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireEnvironment = (value) => {
|
||||
if (!VALID_ENVIRONMENTS.has(value)) {
|
||||
throw new RejectedJobError('env must identify a supported environment')
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireNonEmptyString = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || value.trim() === '') {
|
||||
throw new RejectedJobError(`${fieldName} must be a non-empty string`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const rejectJob = (message) => {
|
||||
throw new RejectedJobError(message)
|
||||
}
|
||||
|
||||
const isRejectedJobError = (error) =>
|
||||
Boolean(error && error.code === 'JOB_REJECTED')
|
||||
|
||||
module.exports = {
|
||||
RejectedJobError,
|
||||
isRejectedJobError,
|
||||
rejectJob,
|
||||
requireEnvironment,
|
||||
requireNonEmptyString,
|
||||
requireObjectId,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "potion-voice",
|
||||
"version": "1.0.0",
|
||||
"description": "This will handle the voice cloning jobs",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "node test/multiTenantIsolation.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bugsnag/js": "^7.3.5",
|
||||
"aws-sdk": "^2.752.0",
|
||||
"fs-extra": "^9.0.1",
|
||||
"mongoose": "^6.8.0",
|
||||
"pm2": "^5.2.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"uuid": "^8.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"aws-code-deploy": "^1.0.11"
|
||||
},
|
||||
"author": "potion Team",
|
||||
"license": "ISC"
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
const assert = require('assert')
|
||||
|
||||
const tenantScope = require('../app/services/utils/tenantScope')
|
||||
const jobValidation = require('../app/services/utils/workerJobValidation')
|
||||
const createVoiceCloningService = require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service')
|
||||
const createCloningProfileService = require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service')
|
||||
const createSynthesizerProfileService = require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service')
|
||||
const createJobService = require('../voice-synthsizer-job-handler/job/job_service')
|
||||
const createSalutationService = require('../voice-synthsizer-job-handler/salutation/salutation_service')
|
||||
|
||||
const TENANT_ID = '64b000000000000000000001'
|
||||
const OTHER_TENANT_ID = '64b000000000000000000002'
|
||||
const DOCUMENT_ID = '64b000000000000000000003'
|
||||
|
||||
const createModelSpy = () => {
|
||||
const calls = {}
|
||||
const model = {
|
||||
find: async (filter) => {
|
||||
calls.find = { filter }
|
||||
return []
|
||||
},
|
||||
findOne: async (filter) => {
|
||||
calls.findOne = { filter }
|
||||
return { _id: DOCUMENT_ID }
|
||||
},
|
||||
findOneAndUpdate: async (filter, update, options) => {
|
||||
calls.findOneAndUpdate = { filter, options, update }
|
||||
return { _id: DOCUMENT_ID }
|
||||
},
|
||||
insertMany: async (data) => {
|
||||
calls.insertMany = { data }
|
||||
return data
|
||||
},
|
||||
updateMany: async (filter, update, options) => {
|
||||
calls.updateMany = { filter, options, update }
|
||||
return { modifiedCount: 1 }
|
||||
},
|
||||
}
|
||||
|
||||
return { calls, model }
|
||||
}
|
||||
|
||||
const expectTenantRejection = async (operation) => {
|
||||
const originalLog = console.log
|
||||
console.log = () => {}
|
||||
try {
|
||||
await assert.rejects(
|
||||
operation(),
|
||||
(error) => error.code === 'TENANT_ID_REQUIRED'
|
||||
)
|
||||
} finally {
|
||||
console.log = originalLog
|
||||
}
|
||||
}
|
||||
|
||||
const verifyTenantCrudService = async (createService) => {
|
||||
const { calls, model } = createModelSpy()
|
||||
const service = createService(model)
|
||||
|
||||
await service.read({ _id: DOCUMENT_ID, userId: TENANT_ID })
|
||||
assert.deepStrictEqual(calls.findOne.filter, {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.update({
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
status: 'processing',
|
||||
})
|
||||
assert.deepStrictEqual(calls.findOneAndUpdate.filter, {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
assert.deepStrictEqual(calls.findOneAndUpdate.update, {
|
||||
$set: { status: 'processing' },
|
||||
})
|
||||
|
||||
await service.find({ status: 'processing', userId: TENANT_ID })
|
||||
assert.deepStrictEqual(calls.find.filter, {
|
||||
status: 'processing',
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.remove({ _id: DOCUMENT_ID, userId: TENANT_ID })
|
||||
assert.deepStrictEqual(calls.findOneAndUpdate.filter, {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.removeMany({ status: 'stale', userId: TENANT_ID })
|
||||
assert.deepStrictEqual(calls.updateMany.filter, {
|
||||
status: 'stale',
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await expectTenantRejection(() => service.read({ _id: DOCUMENT_ID }))
|
||||
}
|
||||
|
||||
const run = async () => {
|
||||
assert.throws(
|
||||
() => tenantScope.scopeFilter({ _id: DOCUMENT_ID }),
|
||||
(error) => error.code === 'TENANT_ID_REQUIRED'
|
||||
)
|
||||
assert.throws(
|
||||
() =>
|
||||
tenantScope.scopeFilter({
|
||||
_id: DOCUMENT_ID,
|
||||
userId: { $ne: OTHER_TENANT_ID },
|
||||
}),
|
||||
(error) => error.code === 'TENANT_ID_REQUIRED'
|
||||
)
|
||||
assert.strictEqual(jobValidation.requireObjectId(TENANT_ID, 'userId'), TENANT_ID)
|
||||
assert.throws(
|
||||
() => jobValidation.requireObjectId('not-an-object-id', 'userId'),
|
||||
(error) => jobValidation.isRejectedJobError(error)
|
||||
)
|
||||
|
||||
await verifyTenantCrudService(createVoiceCloningService)
|
||||
await verifyTenantCrudService(createCloningProfileService)
|
||||
await verifyTenantCrudService(createSynthesizerProfileService)
|
||||
await verifyTenantCrudService(createJobService)
|
||||
|
||||
const jobSpy = createModelSpy()
|
||||
const jobService = createJobService(jobSpy.model)
|
||||
await jobService.insertMany([
|
||||
{ _id: DOCUMENT_ID, userId: TENANT_ID, status: 'created' },
|
||||
])
|
||||
assert.strictEqual(jobSpy.calls.insertMany.data[0].userId, TENANT_ID)
|
||||
await expectTenantRejection(() =>
|
||||
jobService.insertMany([{ _id: DOCUMENT_ID }])
|
||||
)
|
||||
|
||||
const salutationSpy = createModelSpy()
|
||||
const salutationService = createSalutationService(salutationSpy.model)
|
||||
await salutationService.update(
|
||||
{
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
salutationVideo: 'tenant-owned.wav',
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
assert.deepStrictEqual(salutationSpy.calls.findOneAndUpdate.filter, {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
assert.deepStrictEqual(salutationSpy.calls.findOneAndUpdate.update, {
|
||||
$set: { salutationVideo: 'tenant-owned.wav' },
|
||||
})
|
||||
|
||||
console.log('Multi-tenant isolation checks passed')
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -0,0 +1,477 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const {
|
||||
isRejectedJobError,
|
||||
rejectJob,
|
||||
requireEnvironment,
|
||||
requireNonEmptyString,
|
||||
requireObjectId,
|
||||
} = require('../app/services/utils/workerJobValidation')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect to mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const getDatabaseUri = (env) => {
|
||||
const dbUri =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
if (!dbUri) {
|
||||
throw new Error(`MongoDB URI is not configured for ${env}`)
|
||||
}
|
||||
|
||||
return dbUri
|
||||
}
|
||||
|
||||
const getCloudFrontUrl = (env) =>
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
const parseJob = (body) => {
|
||||
if (typeof body !== 'string') {
|
||||
rejectJob('message body must be a JSON string')
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch (error) {
|
||||
rejectJob('message body must contain valid JSON')
|
||||
}
|
||||
}
|
||||
|
||||
const validateJobIdentity = (job) => {
|
||||
if (!job || typeof job !== 'object' || !job._doc) {
|
||||
rejectJob('message body must contain a voice cloning job')
|
||||
}
|
||||
|
||||
return {
|
||||
_id: requireObjectId(job._doc._id, '_id'),
|
||||
env: requireEnvironment(job.env),
|
||||
userAudioProfileId: requireObjectId(
|
||||
job._doc.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
),
|
||||
userId: requireObjectId(job._doc.userId, 'userId'),
|
||||
}
|
||||
}
|
||||
|
||||
const validateJobInput = (metadata, input) => {
|
||||
if (!metadata || typeof metadata !== 'object') {
|
||||
rejectJob('metadata is required')
|
||||
}
|
||||
|
||||
const directoryName = requireNonEmptyString(
|
||||
metadata.directoryName,
|
||||
'metadata.directoryName'
|
||||
)
|
||||
|
||||
if (!Array.isArray(input) || input.length === 0) {
|
||||
rejectJob('input must contain at least one training sample')
|
||||
}
|
||||
|
||||
input.forEach((item, index) => {
|
||||
if (!item || typeof item !== 'object') {
|
||||
rejectJob(`input[${index}] must be an object`)
|
||||
}
|
||||
requireNonEmptyString(item.waveUrl, `input[${index}].waveUrl`)
|
||||
if (typeof item.originalText !== 'string') {
|
||||
rejectJob(`input[${index}].originalText must be a string`)
|
||||
}
|
||||
})
|
||||
|
||||
return { directoryName, input }
|
||||
}
|
||||
|
||||
const acknowledgeRejectedJob = async (receiptHandle, error) => {
|
||||
console.warn('Rejected voice cloning job', { reason: error.message })
|
||||
if (!receiptHandle) return
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
} catch (deleteError) {
|
||||
console.error('Unable to acknowledge rejected voice cloning job', {
|
||||
error: deleteError,
|
||||
})
|
||||
Bugsnag.notify(deleteError)
|
||||
}
|
||||
}
|
||||
|
||||
const closeDatabaseConnection = async () => {
|
||||
if (mongoose.connection.readyState === 0) return
|
||||
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close MongoDB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let receiptHandle
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = parseJob(message.Body)
|
||||
const { _id, env, userAudioProfileId, userId } =
|
||||
validateJobIdentity(job)
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
console.log('userId', userId)
|
||||
console.log('env', env)
|
||||
|
||||
const DB_URI = getDatabaseUri(env)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
rejectJob('referenced records were not found for this tenant')
|
||||
}
|
||||
|
||||
const { directoryName, input } = validateJobInput(
|
||||
voiceCloning.metadata,
|
||||
voiceCloning.input
|
||||
)
|
||||
const cloudFrontUrl = getCloudFrontUrl(env)
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
try {
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
status: 'processing',
|
||||
})
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
status: 'completed',
|
||||
})
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
})
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
training_model_s3_path,
|
||||
})
|
||||
} catch (error) {
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// update the db to set status as error
|
||||
try {
|
||||
await voiceCloningService.update({
|
||||
_id,
|
||||
userId,
|
||||
status: 'error',
|
||||
})
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'error',
|
||||
})
|
||||
} catch (statusError) {
|
||||
console.error('Unable to record voice cloning failure', {
|
||||
error: statusError,
|
||||
})
|
||||
Bugsnag.notify(statusError)
|
||||
}
|
||||
|
||||
return // continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (isRejectedJobError(error)) {
|
||||
await acknowledgeRejectedJob(receiptHandle, error)
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabaseConnection()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice cloning polling error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
processQueue,
|
||||
validateJobIdentity,
|
||||
validateJobInput,
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
requireTenantData,
|
||||
requireTenantDataList,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
requireTenantData,
|
||||
requireTenantDataList,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const newModel = new VoiceCloningModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await VoiceCloningModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => {
|
||||
return {
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
const {
|
||||
isRejectedJobError,
|
||||
rejectJob,
|
||||
requireEnvironment,
|
||||
requireNonEmptyString,
|
||||
requireObjectId,
|
||||
} = require('../app/services/utils/workerJobValidation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect to mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const getDatabaseUri = (env) => {
|
||||
const dbUri =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
if (!dbUri) {
|
||||
throw new Error(`MongoDB URI is not configured for ${env}`)
|
||||
}
|
||||
|
||||
return dbUri
|
||||
}
|
||||
|
||||
const parseJob = (body) => {
|
||||
if (typeof body !== 'string') {
|
||||
rejectJob('message body must be a JSON string')
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch (error) {
|
||||
rejectJob('message body must contain valid JSON')
|
||||
}
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || typeof job !== 'object') {
|
||||
rejectJob('message body must contain a voice synthesizer job')
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrlForPotionAi: job.baseUrlForPotionAi,
|
||||
env: requireEnvironment(job.env),
|
||||
firstName: requireNonEmptyString(job.firstName, 'firstName'),
|
||||
recordingId: requireObjectId(job.recordingId, 'recordingId'),
|
||||
salutationId: requireObjectId(job.salutationId, 'salutationId'),
|
||||
text: requireNonEmptyString(job.text, 'text'),
|
||||
userAudioProfileId: requireObjectId(
|
||||
job.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
),
|
||||
userId: requireObjectId(job.userId, 'userId'),
|
||||
}
|
||||
}
|
||||
|
||||
const getTrainingModelPaths = (userAudioProfile) => {
|
||||
const trainingModelPath = userAudioProfile.training_model_path
|
||||
if (!trainingModelPath || typeof trainingModelPath !== 'object') {
|
||||
rejectJob('audio profile does not have a training model')
|
||||
}
|
||||
|
||||
return {
|
||||
voice_model_config_light_path: requireNonEmptyString(
|
||||
trainingModelPath.voice_model_config_light_path,
|
||||
'training_model_path.voice_model_config_light_path'
|
||||
),
|
||||
voice_model_light_path: requireNonEmptyString(
|
||||
trainingModelPath.voice_model_light_path,
|
||||
'training_model_path.voice_model_light_path'
|
||||
),
|
||||
voice_model_speakers_file_path: requireNonEmptyString(
|
||||
trainingModelPath.voice_model_speakers_file_path,
|
||||
'training_model_path.voice_model_speakers_file_path'
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
const acknowledgeRejectedJob = async (receiptHandle, error) => {
|
||||
console.warn('Rejected voice synthesizer job', { reason: error.message })
|
||||
if (!receiptHandle) return
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
} catch (deleteError) {
|
||||
console.error('Unable to acknowledge rejected voice synthesizer job', {
|
||||
error: deleteError,
|
||||
})
|
||||
Bugsnag.notify(deleteError)
|
||||
}
|
||||
}
|
||||
|
||||
const closeDatabaseConnection = async () => {
|
||||
if (mongoose.connection.readyState === 0) return
|
||||
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close MongoDB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let receiptHandle
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = parseJob(message.Body)
|
||||
try {
|
||||
const {
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = validateJob(job)
|
||||
|
||||
const DB_URI = getDatabaseUri(env)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
|
||||
await Promise.all([
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'completed',
|
||||
}),
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (
|
||||
!userAudioProfile ||
|
||||
!salutationToUpdate ||
|
||||
!recordingToUpdate
|
||||
) {
|
||||
rejectJob('referenced records were not found for this tenant')
|
||||
}
|
||||
|
||||
const trainingModelPaths = getTrainingModelPaths(userAudioProfile)
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
if (userAudioProfile) {
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
voice_model_speakers_file_path, // name for speakers embeddings file path
|
||||
} = trainingModelPaths
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
const aiResponse = await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace(
|
||||
'-',
|
||||
'_'
|
||||
)}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create new entry with the s3 path to salutation collection for the user and its profile id
|
||||
// upsert the salutation
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName: firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
if (
|
||||
salutationToUpdate &&
|
||||
salutationToUpdate.deleted === false &&
|
||||
recordingToUpdate
|
||||
) {
|
||||
const jobsToInsert = []
|
||||
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl ||
|
||||
recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: salutationToUpdate._id,
|
||||
firstName: firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: salutationToUpdate._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
jobsToInsert.push({
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
userId,
|
||||
salutationId: salutationToUpdate._id,
|
||||
metadata: jobData,
|
||||
})
|
||||
|
||||
// create the job for the ai to create processing
|
||||
if (jobsToInsert.length) {
|
||||
await jobService.insertMany(jobsToInsert)
|
||||
}
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} else {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`audio profile training model not found ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
|
||||
return // to continue working on new jobs
|
||||
}
|
||||
} catch (error) {
|
||||
if (isRejectedJobError(error)) throw error
|
||||
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
return // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (isRejectedJobError(error)) {
|
||||
await acknowledgeRejectedJob(receiptHandle, error)
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabaseConnection()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice synthesizer polling error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getTrainingModelPaths,
|
||||
init,
|
||||
processQueue,
|
||||
validateJob,
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
const mongoose = require('mongoose')
|
||||
const Schema = mongoose.Schema
|
||||
const JobSchema = Schema(
|
||||
{
|
||||
recordingId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: false
|
||||
},
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true
|
||||
},
|
||||
salutationId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: false
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: 'ai-job'
|
||||
},
|
||||
firstName: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
weight: {
|
||||
type: Number,
|
||||
default: 0
|
||||
},
|
||||
email: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: 'created'
|
||||
},
|
||||
metadata: {
|
||||
type: Schema.Types.Mixed,
|
||||
default: null
|
||||
},
|
||||
deleted: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
default: false
|
||||
}
|
||||
},
|
||||
{
|
||||
timestamps: true
|
||||
}
|
||||
)
|
||||
|
||||
module.exports = mongoose.model('Job', JobSchema)
|
||||
@@ -0,0 +1,149 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
requireTenantData,
|
||||
requireTenantDataList,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Job) => async (jobData) => {
|
||||
try {
|
||||
requireTenantData(jobData)
|
||||
const newJob = new Job({ ...jobData })
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData) => {
|
||||
try {
|
||||
requireTenantDataList(jobData)
|
||||
const inserted = await Job.insertMany(jobData)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (Job) => async (filter) => {
|
||||
try {
|
||||
const foundJob = await Job.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (Job) => async (filter) => {
|
||||
try {
|
||||
const foundJobs = await Job.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (Job) => async (job) => {
|
||||
try {
|
||||
requireTenantData(job)
|
||||
const { _id, userId, ...updates } = job
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Job) => async (filter) => {
|
||||
try {
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (Job) => async (filter) => {
|
||||
try {
|
||||
const updatedJob = await Job.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (Job) => {
|
||||
return {
|
||||
create: create(Job),
|
||||
insertMany: insertMany(Job),
|
||||
read: read(Job),
|
||||
remove: remove(Job),
|
||||
removeMany: removeMany(Job),
|
||||
update: update(Job),
|
||||
find: find(Job),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
const {
|
||||
requireTenantId,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const withoutTenantIdentity = (salutation) => {
|
||||
const updates =
|
||||
typeof salutation.toObject === 'function'
|
||||
? salutation.toObject()
|
||||
: { ...salutation }
|
||||
|
||||
delete updates._id
|
||||
delete updates.userId
|
||||
return updates
|
||||
}
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
requireTenantId(userId)
|
||||
const newSalutation = new Salutation({ ...salutationData, userId })
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
requireTenantId(userId)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ _id: salutation._id, userId, deleted: false },
|
||||
{ $set: withoutTenantIdentity(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
requireTenantId(userId)
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id, userId, deleted: false }
|
||||
: { transcriptId: salutation.transcriptId, userId, deleted: false }
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
findQuery,
|
||||
{ $set: withoutTenantIdentity(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
requireTenantId(userId)
|
||||
const salutation = await read(Salutation)({
|
||||
firstName,
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
})
|
||||
if (salutation) {
|
||||
salutation.salutationVideo = salutationVideo
|
||||
return await update(Salutation)(salutation, userId)
|
||||
} else {
|
||||
return await create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Salutation) => async (filter, userId) => {
|
||||
requireTenantId(userId)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ ...filter, userId, deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
module.exports = (Salutation) => {
|
||||
return {
|
||||
create: create(Salutation),
|
||||
read: read(Salutation),
|
||||
remove: remove(Salutation),
|
||||
update: update(Salutation),
|
||||
updateOrCreate: updateOrCreate(Salutation),
|
||||
find: find(Salutation),
|
||||
modify: modify(Salutation),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
requireTenantData,
|
||||
requireTenantDataList,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantDataList(data)
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeFilter(filter),
|
||||
deleted: false
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeFilter(filter),
|
||||
deleted: false
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireTenantData(data)
|
||||
const { _id, userId, ...updates } = data
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...scopeFilter(filter), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning handler reads VoiceCloning and UserAudioProfile with both _id and userId (voice-cloning-job-handler/index.js:218-228), and every handler update supplies both IDs (lines 248-257, 357-376, 393-417). The corresponding services filter updates by _id and userId.
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads and the RecordingSalutation update include record _id and userId (voice-synthsizer-job-handler/index.js:191-200, 272-283). That userId comes from the queue job, however, rather than from the initial UserAudioProfile result. The profile read requires the same payload userId, so successful reads are tenant-consistent, but the required profile-derived scoping is absent.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesizer requires job.userId during validation and includes it in the initial profile read (voice-synthsizer-job-handler/index.js:104, 184-190). The profile service also rejects an ID-only read. The base handler fetched the profile by ID and obtained userId from the result. A focused check confirmed that the final handler rejects a message without top-level userId before that lookup.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Both handlers reject missing or mismatched referenced records before file creation, audio generation, uploads, or database writes (voice-cloning-job-handler/index.js:218-257; voice-synthsizer-job-handler/index.js:184-225). Rejection then acknowledges the SQS message. The synthesizer's incorrect tenant source is assessed in the tenant-resolution criteria.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Validation and database errors are caught within processQueue, connection closure is guarded, and each polling iteration has its own catch in both handlers. Database connection retries eventually throw into those catches. Repository tests and JavaScript syntax checks passed, though no live SQS/Mongo poller was run.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning handler retains an error-status update on the requesting VoiceCloning job, filtered by its _id and userId (voice-cloning-job-handler/index.js:398-424). It runs after ownership checks. Rejection paths log and acknowledge messages without downstream writes.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The agent's final transcript message (step 46) concisely describes scoping, pre-processing record checks, rejected-job handling, polling resilience, and the new queue userId fields. It clearly describes the approach implemented, despite the missing profile-derived tenant resolution.
|
||||
|
||||
## Closing
|
||||
|
||||
The agent's npm test passes, but its tests do not exercise the synthesizer's required profile-derived tenant context.
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning handler reads VoiceCloning and UserAudioProfile with both _id and userId (voice-cloning-job-handler/index.js:218-228), and every handler update supplies both IDs (lines 248-257, 357-376, 393-417). The corresponding services filter updates by _id and userId.
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads and the RecordingSalutation update include record _id and userId (voice-synthsizer-job-handler/index.js:191-200, 272-283). That userId comes from the queue job, however, rather than from the initial UserAudioProfile result. The profile read requires the same payload userId, so successful reads are tenant-consistent, but the required profile-derived scoping is absent.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesizer requires job.userId during validation and includes it in the initial profile read (voice-synthsizer-job-handler/index.js:104, 184-190). The profile service also rejects an ID-only read. The base handler fetched the profile by ID and obtained userId from the result. A focused check confirmed that the final handler rejects a message without top-level userId before that lookup.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Both handlers reject missing or mismatched referenced records before file creation, audio generation, uploads, or database writes (voice-cloning-job-handler/index.js:218-257; voice-synthsizer-job-handler/index.js:184-225). Rejection then acknowledges the SQS message. The synthesizer's incorrect tenant source is assessed in the tenant-resolution criteria.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Validation and database errors are caught within processQueue, connection closure is guarded, and each polling iteration has its own catch in both handlers. Database connection retries eventually throw into those catches. Repository tests and JavaScript syntax checks passed, though no live SQS/Mongo poller was run.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning handler retains an error-status update on the requesting VoiceCloning job, filtered by its _id and userId (voice-cloning-job-handler/index.js:398-424). It runs after ownership checks. Rejection paths log and acknowledge messages without downstream writes.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The agent's final transcript message (step 46) concisely describes scoping, pre-processing record checks, rejected-job handling, polling resilience, and the new queue userId fields. It clearly describes the approach implemented, despite the missing profile-derived tenant resolution.
|
||||
|
||||
## Closing
|
||||
|
||||
The agent's npm test passes, but its tests do not exercise the synthesizer's required profile-derived tenant context.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:54:42Z",
|
||||
"grader_mode": "rubric-trinary",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "rubric-trinary",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "rubric-criteria.md",
|
||||
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
|
||||
"render_grade_file": "render-rubric-grade.py",
|
||||
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc4-5627-7152-aefe-c554161a54db", "usage": {"input_tokens": 871372, "cached_input_tokens": 777644, "cache_write_input_tokens": 93686, "output_tokens": 9106, "reasoning_output_tokens": 4942}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc4-5627-7152-aefe-c554161a54db", "usage": {"input_tokens": 871372, "cached_input_tokens": 777644, "cache_write_input_tokens": 93686, "output_tokens": 9106, "reasoning_output_tokens": 4942}}
|
||||
@@ -0,0 +1,6 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.89
|
||||
mean: 0.8900
|
||||
canonical_sample: 1
|
||||
correctness_mean: (none)
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.9SLZjT5K"))
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.9SLZjT5K"))
|
||||
@@ -0,0 +1 @@
|
||||
0.89
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.8900}
|
||||
@@ -0,0 +1 @@
|
||||
0.8900
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"form": "trinary",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "cloning-tenant-isolation",
|
||||
"rationale": "The cloning handler reads VoiceCloning and UserAudioProfile with both _id and userId (voice-cloning-job-handler/index.js:218-228), and every handler update supplies both IDs (lines 248-257, 357-376, 393-417). The corresponding services filter updates by _id and userId.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "synthesis-tenant-isolation-queries-updates",
|
||||
"rationale": "RecordingSalutation and Recording reads and the RecordingSalutation update include record _id and userId (voice-synthsizer-job-handler/index.js:191-200, 272-283). That userId comes from the queue job, however, rather than from the initial UserAudioProfile result. The profile read requires the same payload userId, so successful reads are tenant-consistent, but the required profile-derived scoping is absent.",
|
||||
"verdict": "partial"
|
||||
},
|
||||
{
|
||||
"id": "initial-profile-tenant-resolution",
|
||||
"rationale": "The synthesizer requires job.userId during validation and includes it in the initial profile read (voice-synthsizer-job-handler/index.js:104, 184-190). The profile service also rejects an ID-only read. The base handler fetched the profile by ID and obtained userId from the result. A focused check confirmed that the final handler rejects a message without top-level userId before that lookup.",
|
||||
"verdict": "fail"
|
||||
},
|
||||
{
|
||||
"id": "prevent-unauthorized-side-effects",
|
||||
"rationale": "Both handlers reject missing or mismatched referenced records before file creation, audio generation, uploads, or database writes (voice-cloning-job-handler/index.js:218-257; voice-synthsizer-job-handler/index.js:184-225). Rejection then acknowledges the SQS message. The synthesizer's incorrect tenant source is assessed in the tenant-resolution criteria.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "worker-loop-crash-prevention",
|
||||
"rationale": "Validation and database errors are caught within processQueue, connection closure is guarded, and each polling iteration has its own catch in both handlers. Database connection retries eventually throw into those catches. Repository tests and JavaScript syntax checks passed, though no live SQS/Mongo poller was run.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "error-status-lifecycle-logging",
|
||||
"rationale": "The cloning handler retains an error-status update on the requesting VoiceCloning job, filtered by its _id and userId (voice-cloning-job-handler/index.js:398-424). It runs after ownership checks. Rejection paths log and acknowledge messages without downstream writes.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "refactor-summary-clarity",
|
||||
"rationale": "The agent's final transcript message (step 46) concisely describes scoping, pre-processing record checks, rejected-job handling, polling resilience, and the new queue userId fields. It clearly describes the approach implemented, despite the missing profile-derived tenant resolution.",
|
||||
"verdict": "pass"
|
||||
}
|
||||
],
|
||||
"closing": "The agent's npm test passes, but its tests do not exercise the synthesizer's required profile-derived tenant context.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-rubric-grade/2.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"form": "trinary",
|
||||
"criteria": [
|
||||
{
|
||||
"id": "cloning-tenant-isolation",
|
||||
"rationale": "The cloning handler reads VoiceCloning and UserAudioProfile with both _id and userId (voice-cloning-job-handler/index.js:218-228), and every handler update supplies both IDs (lines 248-257, 357-376, 393-417). The corresponding services filter updates by _id and userId.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "synthesis-tenant-isolation-queries-updates",
|
||||
"rationale": "RecordingSalutation and Recording reads and the RecordingSalutation update include record _id and userId (voice-synthsizer-job-handler/index.js:191-200, 272-283). That userId comes from the queue job, however, rather than from the initial UserAudioProfile result. The profile read requires the same payload userId, so successful reads are tenant-consistent, but the required profile-derived scoping is absent.",
|
||||
"verdict": "partial"
|
||||
},
|
||||
{
|
||||
"id": "initial-profile-tenant-resolution",
|
||||
"rationale": "The synthesizer requires job.userId during validation and includes it in the initial profile read (voice-synthsizer-job-handler/index.js:104, 184-190). The profile service also rejects an ID-only read. The base handler fetched the profile by ID and obtained userId from the result. A focused check confirmed that the final handler rejects a message without top-level userId before that lookup.",
|
||||
"verdict": "fail"
|
||||
},
|
||||
{
|
||||
"id": "prevent-unauthorized-side-effects",
|
||||
"rationale": "Both handlers reject missing or mismatched referenced records before file creation, audio generation, uploads, or database writes (voice-cloning-job-handler/index.js:218-257; voice-synthsizer-job-handler/index.js:184-225). Rejection then acknowledges the SQS message. The synthesizer's incorrect tenant source is assessed in the tenant-resolution criteria.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "worker-loop-crash-prevention",
|
||||
"rationale": "Validation and database errors are caught within processQueue, connection closure is guarded, and each polling iteration has its own catch in both handlers. Database connection retries eventually throw into those catches. Repository tests and JavaScript syntax checks passed, though no live SQS/Mongo poller was run.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "error-status-lifecycle-logging",
|
||||
"rationale": "The cloning handler retains an error-status update on the requesting VoiceCloning job, filtered by its _id and userId (voice-cloning-job-handler/index.js:398-424). It runs after ownership checks. Rejection paths log and acknowledge messages without downstream writes.",
|
||||
"verdict": "pass"
|
||||
},
|
||||
{
|
||||
"id": "refactor-summary-clarity",
|
||||
"rationale": "The agent's final transcript message (step 46) concisely describes scoping, pre-processing record checks, rejected-job handling, polling resilience, and the new queue userId fields. It clearly describes the approach implemented, despite the missing profile-derived tenant resolution.",
|
||||
"verdict": "pass"
|
||||
}
|
||||
],
|
||||
"closing": "The agent's npm test passes, but its tests do not exercise the synthesizer's required profile-derived tenant context.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-rubric-grade/2.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
Captured 13 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-rubric-grade: ok reward=0.89 form=trinary criteria=7 excluded_extra_credit=0 partial_extra_credit=0 total_weight=41
|
||||
grader sample 1: 0.89
|
||||
reward: 0.8900 correctness: (none)
|
||||
0.8900
|
||||
{"reward": 0.8900}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "30ab2ac3-aa1c-4501-bfd4-b9465601df01",
|
||||
"started_at": "2026-10-14T18:54:37.259481",
|
||||
"updated_at": "2026-10-14T18:56:58.574280",
|
||||
"finished_at": "2026-10-14T18:56:58.574280",
|
||||
"n_total_trials": 1,
|
||||
"stats": {
|
||||
"n_completed_trials": 1,
|
||||
"n_errored_trials": 0,
|
||||
"n_running_trials": 0,
|
||||
"n_pending_trials": 0,
|
||||
"n_cancelled_trials": 0,
|
||||
"n_retries": 0,
|
||||
"evals": {
|
||||
"replay__adhoc": {
|
||||
"n_trials": 1,
|
||||
"n_errors": 0,
|
||||
"metrics": [
|
||||
{
|
||||
"mean": 0.89
|
||||
}
|
||||
],
|
||||
"pass_at_k": {},
|
||||
"reward_stats": {
|
||||
"reward": {
|
||||
"0.89": [
|
||||
"potion-voice-user-ownership__pqHcH9x"
|
||||
]
|
||||
}
|
||||
},
|
||||
"exception_stats": {}
|
||||
}
|
||||
},
|
||||
"n_input_tokens": null,
|
||||
"n_cache_tokens": null,
|
||||
"n_output_tokens": null,
|
||||
"cost_usd": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"job_name": "regrade-reward-0.6800-7prhyuz-1792004339-27643",
|
||||
"jobs_dir": "harbor-jobs/reward-0.6800-7prhyuz",
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"agents": [
|
||||
{
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7prhyuz",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"created_at": "2026-10-14T18:59:00.485003Z",
|
||||
"harbor": {
|
||||
"version": "0.20.0",
|
||||
"is_editable": false
|
||||
},
|
||||
"n_concurrent_trials": 4,
|
||||
"retry": {
|
||||
"max_retries": 0,
|
||||
"exclude_exceptions": [
|
||||
"ModelNotFoundError",
|
||||
"VerifierOutputParseError",
|
||||
"AgentSafetyRefusalError",
|
||||
"AgentTimeoutError",
|
||||
"ApiUsageLimitError",
|
||||
"RewardFileNotFoundError",
|
||||
"AgentAuthenticationError",
|
||||
"VerifierTimeoutError",
|
||||
"RewardFileEmptyError"
|
||||
],
|
||||
"wait_multiplier": 1.0,
|
||||
"min_wait_sec": 1.0,
|
||||
"max_wait_sec": 60.0
|
||||
},
|
||||
"trials": [
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7prhyuz",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"source": "/logs/artifacts",
|
||||
"destination": "artifacts/logs/artifacts",
|
||||
"type": "directory",
|
||||
"status": "empty",
|
||||
"service": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__5PnrMxR",
|
||||
"trials_dir": "harbor-jobs/reward-0.6800-7prhyuz/regrade-reward-0.6800-7prhyuz-1792004339-27643",
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7prhyuz",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "212e56af-550f-4a9b-8950-0ddbe903c11d"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:9ccddb94984a361137fe8856cccb6f4c957d3e03e9e0181f22eeae2206dfe56e",
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7prhyuz",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "aebfefa5-db77-4749-8f5e-5380cec4b979",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__5PnrMxR",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.6800-7prhyuz/regrade-reward-0.6800-7prhyuz-1792004339-27643/potion-voice-user-ownership__5PnrMxR",
|
||||
"task_id": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "4ab739def58149c933bf97209881c1c8d44b0c7a714519270af06dc8ebd2a620",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__5PnrMxR",
|
||||
"trials_dir": "harbor-jobs/reward-0.6800-7prhyuz/regrade-reward-0.6800-7prhyuz-1792004339-27643",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "replay_agent:ReplayAgent",
|
||||
"model_name": null,
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7prhyuz",
|
||||
"source_agent_import_path": "codex_agent:SystemNodeCodex",
|
||||
"source_model_name": "gpt-5.6-sol"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": false,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"GRADER_MODE": "rubric-trinary",
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "212e56af-550f-4a9b-8950-0ddbe903c11d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "replay",
|
||||
"version": "1.0.0",
|
||||
"model_info": null
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": null,
|
||||
"n_cache_tokens": null,
|
||||
"n_output_tokens": null,
|
||||
"cost_usd": null,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.89
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:59:00.756574Z",
|
||||
"finished_at": "2026-10-14T19:02:04.118782Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:59:00.859832Z",
|
||||
"finished_at": "2026-10-14T18:59:04.507257Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:59:04.507312Z",
|
||||
"finished_at": "2026-10-14T18:59:04.507372Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:59:04.507438Z",
|
||||
"finished_at": "2026-10-14T18:59:04.921427Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:59:05.476172Z",
|
||||
"finished_at": "2026-10-14T19:01:59.845143Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,410 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const validateObjectId = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
|
||||
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
|
||||
}
|
||||
}
|
||||
|
||||
const getJobContext = (job) => {
|
||||
if (!job || !job._doc || typeof job._doc !== 'object') {
|
||||
throw new RejectedJobError('Invalid voice cloning job payload')
|
||||
}
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
|
||||
validateObjectId(_id, '_id')
|
||||
validateObjectId(userAudioProfileId, 'userAudioProfileId')
|
||||
validateObjectId(userId, 'userId')
|
||||
|
||||
return { metadata, input, _id, userAudioProfileId, userId, env: job.env }
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let message
|
||||
let messageDeleted = false
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
message = response.Messages[0]
|
||||
|
||||
let job
|
||||
try {
|
||||
job = JSON.parse(message.Body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Invalid JSON in voice cloning job')
|
||||
}
|
||||
|
||||
console.log('job===', job)
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId, env } =
|
||||
getJobContext(job)
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [voiceCloningJob, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!voiceCloningJob || !userAudioProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job does not belong to the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
messageDeleted = true
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
try {
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
await voiceCloningService.update({ _id, status: 'processing' }, userId)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update({ _id, status: 'completed' }, userId)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
training_model_s3_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
} catch (error) {
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// Keep failure handling tenant-scoped and do not let a secondary
|
||||
// status update failure stop the polling loop.
|
||||
await Promise.allSettled([
|
||||
voiceCloningService.update({ _id, status: 'error' }, userId),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
if (message && !messageDeleted) {
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
} catch (deleteError) {
|
||||
console.error('Unable to delete rejected voice cloning job', {
|
||||
error: deleteError,
|
||||
})
|
||||
Bugsnag.notify(deleteError)
|
||||
}
|
||||
}
|
||||
console.warn('Rejected voice cloning job', { reason: error.message })
|
||||
} else {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice cloning worker error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create an audio profile')
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create audio profiles')
|
||||
}
|
||||
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read an audio profile'
|
||||
)
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find audio profiles'
|
||||
)
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(UserAudioProfileModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update an audio profile'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove an audio profile'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove audio profiles'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => ({
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create a voice clone')
|
||||
const newModel = new VoiceCloningModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create voice clones')
|
||||
}
|
||||
|
||||
const inserted = await VoiceCloningModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read a voice clone'
|
||||
)
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find voice clones'
|
||||
)
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(VoiceCloningModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update a voice clone'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove a voice clone'
|
||||
)
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove voice clones'
|
||||
)
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => ({
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
})
|
||||
@@ -0,0 +1,313 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const validateObjectId = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
|
||||
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
|
||||
}
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || typeof job !== 'object') {
|
||||
throw new RejectedJobError('Invalid voice synthesizer job payload')
|
||||
}
|
||||
|
||||
validateObjectId(job.userId, 'userId')
|
||||
validateObjectId(job.userAudioProfileId, 'userAudioProfileId')
|
||||
validateObjectId(job.salutationId, 'salutationId')
|
||||
validateObjectId(job.recordingId, 'recordingId')
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
|
||||
let job
|
||||
try {
|
||||
job = JSON.parse(message.Body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Invalid JSON in voice synthesizer job')
|
||||
}
|
||||
validateJob(job)
|
||||
|
||||
try {
|
||||
const {
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
const userAudioProfile = await userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'completed',
|
||||
})
|
||||
if (userAudioProfile) {
|
||||
const { training_model_path } = userAudioProfile
|
||||
|
||||
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!salutationToUpdate || !recordingToUpdate) {
|
||||
throw new RejectedJobError(
|
||||
'Recording data does not belong to the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
voice_model_speakers_file_path, // name for speakers embeddings file path
|
||||
} = training_model_path
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
const aiResponse = await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create new entry with the s3 path to salutation collection for the user and its profile id
|
||||
// upsert the salutation
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName: firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
const jobsToInsert = []
|
||||
|
||||
const updatedRecordingSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedRecordingSalutation) {
|
||||
throw new RejectedJobError(
|
||||
'Recording salutation is no longer available for this userId'
|
||||
)
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl ||
|
||||
recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: salutationToUpdate._id,
|
||||
firstName: firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: salutationToUpdate._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
jobsToInsert.push({
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
userId,
|
||||
salutationId: salutationToUpdate._id,
|
||||
metadata: jobData,
|
||||
})
|
||||
|
||||
// create the job for the ai to create processing
|
||||
if (jobsToInsert.length) {
|
||||
await jobService.insertMany(jobsToInsert)
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} else {
|
||||
throw new RejectedJobError(
|
||||
'Audio profile does not belong to the supplied userId or is not completed'
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn('Rejected voice synthesizer job', {
|
||||
reason: error.message,
|
||||
})
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn('Rejected voice synthesizer job', {
|
||||
reason: error.message,
|
||||
})
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice synthesizer worker error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,169 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const create = (Job) => async (jobData) => {
|
||||
try {
|
||||
if (!jobData.userId) throw new Error('userId is required to create a job')
|
||||
|
||||
const newJob = new Job({ ...jobData })
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData) => {
|
||||
try {
|
||||
if (!jobData.every((job) => job.userId))
|
||||
throw new Error('userId is required to create jobs')
|
||||
|
||||
const inserted = await Job.insertMany(jobData)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to read a job')
|
||||
|
||||
const foundJob = await Job.findOne({
|
||||
...filter,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to find jobs')
|
||||
|
||||
const foundJobs = await Job.find({
|
||||
...filter,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(Job) =>
|
||||
async (job, userId = job.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to update a job')
|
||||
|
||||
const { _id, ...updates } = job
|
||||
delete updates.userId
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to remove a job')
|
||||
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ ...filter, userId },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to remove jobs')
|
||||
|
||||
const updatedJob = await Job.updateMany(
|
||||
{ ...filter, userId },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (Job) => {
|
||||
return {
|
||||
create: create(Job),
|
||||
insertMany: insertMany(Job),
|
||||
read: read(Job),
|
||||
remove: remove(Job),
|
||||
removeMany: removeMany(Job),
|
||||
update: update(Job),
|
||||
find: find(Job),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const getUpdates = (data) => {
|
||||
const updates =
|
||||
typeof data.toObject === 'function' ? data.toObject() : { ...data }
|
||||
delete updates._id
|
||||
delete updates.userId
|
||||
return updates
|
||||
}
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const tenantId = requireUserId(userId, 'create a salutation')
|
||||
const newSalutation = new Salutation({
|
||||
...salutationData,
|
||||
userId: tenantId,
|
||||
})
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(userId || filter.userId, 'read a salutation')
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(userId || filter.userId, 'find salutations')
|
||||
const foundSalutations = await Salutation.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const tenantId = requireUserId(userId, 'update a salutation')
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ _id: salutation._id, userId: tenantId, deleted: false },
|
||||
{ $set: getUpdates(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify =
|
||||
(Salutation) =>
|
||||
async (salutation = {}, userId) => {
|
||||
const tenantId = requireUserId(
|
||||
userId || salutation.userId,
|
||||
'modify a salutation'
|
||||
)
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id, userId: tenantId, deleted: false }
|
||||
: {
|
||||
transcriptId: salutation.transcriptId,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
}
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
findQuery,
|
||||
{ $set: getUpdates(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
const tenantId = requireUserId(userId, 'upsert a salutation')
|
||||
const salutation = await read(Salutation)(
|
||||
{ firstName, userAudioProfileId },
|
||||
tenantId
|
||||
)
|
||||
|
||||
if (salutation) {
|
||||
salutation.salutationVideo = salutationVideo
|
||||
return update(Salutation)(salutation, tenantId)
|
||||
}
|
||||
|
||||
return create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
tenantId
|
||||
)
|
||||
}
|
||||
|
||||
const remove =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove a salutation'
|
||||
)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId, deleted: false },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
module.exports = (Salutation) => ({
|
||||
create: create(Salutation),
|
||||
read: read(Salutation),
|
||||
remove: remove(Salutation),
|
||||
update: update(Salutation),
|
||||
updateOrCreate: updateOrCreate(Salutation),
|
||||
find: find(Salutation),
|
||||
modify: modify(Salutation),
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create an audio profile')
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create audio profiles')
|
||||
}
|
||||
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read an audio profile'
|
||||
)
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find audio profiles'
|
||||
)
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(UserAudioProfileModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update an audio profile'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove an audio profile'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove audio profiles'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => ({
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning handler reads VoiceCloning by {_id, userId, userAudioProfileId} and UserAudioProfile by {_id, userId} before processing (voice-cloning-job-handler/index.js:151-167). Every live status/model update passes userId (lines 187-194, 294, 304-310, 328-334, 347-355), and both service update filters contain _id and userId (voice_cloning_service.js:101-104; user_audio_profile_service.js:101-104).
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads, plus the RecordingSalutation update, all use {_id, userId} (voice-synthsizer-job-handler/index.js:128-139, 196-209). Salutation and Job writes also carry that userId. However it is destructured from the queue message at lines 96-106, not derived from the fetched UserAudioProfile; the handler never reads userAudioProfile.userId. This misses the specified tenant-source contract, even though the profile lookup requires the supplied userId to match.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesis handler rejects messages without top-level job.userId at validateJob (voice-synthsizer-job-handler/index.js:65-74), then calls userAudioProfileService.read with {_id: userAudioProfileId, userId, status: 'completed'} (lines 120-124). The service itself rejects an ID-only read (user_audio_profile_service.js:42-53). The base handler accepted profile-ID-only lookup and took userId from the returned profile (base:index.js:96-103); the agent's final message explicitly says legacy messages without userId are rejected.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Cloning rejects a missing or mismatched clone/profile before creating log or training directories, downloading files, or updating models (voice-cloning-job-handler/index.js:151-185). Synthesis checks the profile and both tenant-scoped recording records before mkdir, Python synthesis, S3 upload, salutation mutation, or job insertion (voice-synthsizer-job-handler/index.js:120-155, 163-247). An independent mocked worker run confirmed rejected and mismatched-record messages made no file, audio, S3, or database mutation calls.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Both processQueue functions catch JSON/validation and database errors, close MongoDB in guarded finally blocks, and their init loops catch per-iteration errors before polling again (cloning index.js:360-408; synthesis index.js:273-310). connectDB now throws after bounded retries instead of leaving its promise pending. The mocked rejection exercise called each processQueue twice successfully, including malformed/missing-tenant messages.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning error path retains a tenant-scoped status: 'error' update on the requesting VoiceCloning job (voice-cloning-job-handler/index.js:344-355); its service applies {_id, userId, deleted:false} to that update (voice_cloning_service.js:101-104). This permitted lifecycle write does not count as an unauthorized downstream mutation. Explicit ownership rejections are logged without forcing a status write.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The final assistant message concisely describes userId-scoped reads/writes, ownership checks before processing, protected update helpers, and polling resilience across both handlers. It also plainly discloses that synthesis now requires top-level userId and rejects older messages.
|
||||
|
||||
## Closing
|
||||
|
||||
Syntax and diff checks passed; no repository test script or live MongoDB/SQS integration environment was available.
|
||||
@@ -0,0 +1,33 @@
|
||||
Rubric score (trinary): 0.89 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
|
||||
|
||||
## cloning-tenant-isolation — PASS
|
||||
|
||||
The cloning handler reads VoiceCloning by {_id, userId, userAudioProfileId} and UserAudioProfile by {_id, userId} before processing (voice-cloning-job-handler/index.js:151-167). Every live status/model update passes userId (lines 187-194, 294, 304-310, 328-334, 347-355), and both service update filters contain _id and userId (voice_cloning_service.js:101-104; user_audio_profile_service.js:101-104).
|
||||
|
||||
## synthesis-tenant-isolation-queries-updates — PARTIAL
|
||||
|
||||
RecordingSalutation and Recording reads, plus the RecordingSalutation update, all use {_id, userId} (voice-synthsizer-job-handler/index.js:128-139, 196-209). Salutation and Job writes also carry that userId. However it is destructured from the queue message at lines 96-106, not derived from the fetched UserAudioProfile; the handler never reads userAudioProfile.userId. This misses the specified tenant-source contract, even though the profile lookup requires the supplied userId to match.
|
||||
|
||||
## initial-profile-tenant-resolution — FAIL
|
||||
|
||||
The synthesis handler rejects messages without top-level job.userId at validateJob (voice-synthsizer-job-handler/index.js:65-74), then calls userAudioProfileService.read with {_id: userAudioProfileId, userId, status: 'completed'} (lines 120-124). The service itself rejects an ID-only read (user_audio_profile_service.js:42-53). The base handler accepted profile-ID-only lookup and took userId from the returned profile (base:index.js:96-103); the agent's final message explicitly says legacy messages without userId are rejected.
|
||||
|
||||
## prevent-unauthorized-side-effects — PASS
|
||||
|
||||
Cloning rejects a missing or mismatched clone/profile before creating log or training directories, downloading files, or updating models (voice-cloning-job-handler/index.js:151-185). Synthesis checks the profile and both tenant-scoped recording records before mkdir, Python synthesis, S3 upload, salutation mutation, or job insertion (voice-synthsizer-job-handler/index.js:120-155, 163-247). An independent mocked worker run confirmed rejected and mismatched-record messages made no file, audio, S3, or database mutation calls.
|
||||
|
||||
## worker-loop-crash-prevention — PASS
|
||||
|
||||
Both processQueue functions catch JSON/validation and database errors, close MongoDB in guarded finally blocks, and their init loops catch per-iteration errors before polling again (cloning index.js:360-408; synthesis index.js:273-310). connectDB now throws after bounded retries instead of leaving its promise pending. The mocked rejection exercise called each processQueue twice successfully, including malformed/missing-tenant messages.
|
||||
|
||||
## error-status-lifecycle-logging — PASS
|
||||
|
||||
The cloning error path retains a tenant-scoped status: 'error' update on the requesting VoiceCloning job (voice-cloning-job-handler/index.js:344-355); its service applies {_id, userId, deleted:false} to that update (voice_cloning_service.js:101-104). This permitted lifecycle write does not count as an unauthorized downstream mutation. Explicit ownership rejections are logged without forcing a status write.
|
||||
|
||||
## refactor-summary-clarity — PASS
|
||||
|
||||
The final assistant message concisely describes userId-scoped reads/writes, ownership checks before processing, protected update helpers, and polling resilience across both handlers. It also plainly discloses that synthesis now requires top-level userId and rejects older messages.
|
||||
|
||||
## Closing
|
||||
|
||||
Syntax and diff checks passed; no repository test script or live MongoDB/SQS integration environment was available.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:59:05Z",
|
||||
"grader_mode": "rubric-trinary",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "rubric-trinary",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "rubric-criteria.md",
|
||||
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
|
||||
"render_grade_file": "render-rubric-grade.py",
|
||||
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc8-54d9-78a1-8b97-7a188e63724c", "usage": {"input_tokens": 1059652, "cached_input_tokens": 977112, "cache_write_input_tokens": 82489, "output_tokens": 11986, "reasoning_output_tokens": 6148}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13bc8-54d9-78a1-8b97-7a188e63724c", "usage": {"input_tokens": 1059652, "cached_input_tokens": 977112, "cache_write_input_tokens": 82489, "output_tokens": 11986, "reasoning_output_tokens": 6148}}
|
||||
@@ -0,0 +1,6 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.89
|
||||
mean: 0.8900
|
||||
canonical_sample: 1
|
||||
correctness_mean: (none)
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.P2Wdku8D"))
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.P2Wdku8D"))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user