Compare commits
85 Commits
1.0.1_rest
...
30cbf18f75
| Author | SHA1 | Date | |
|---|---|---|---|
| 30cbf18f75 | |||
| 39a20d4ea3 | |||
| fa8c47f917 | |||
| 5de8ad776b | |||
| 6671ef4d77 | |||
| ba4cb8c0d3 | |||
| 8c688f469e | |||
| fb8dd45b94 | |||
| baefe3ca8a | |||
| 20d5cd9c86 | |||
| 8cda63af50 | |||
| facbe4f700 | |||
| 45a935a84b | |||
| 5c77492d40 | |||
| d20c019473 | |||
| 28076f945a | |||
| 4435f64af9 | |||
| 6ec7a3daec | |||
| 4e2738054a | |||
| eef5281740 | |||
| bf4d84115a | |||
| 14988c6b72 | |||
| c195bf7975 | |||
| 0e8616eeda | |||
| a9933b06ee | |||
| edbc7479bc | |||
| 577b857fed | |||
| 6a6063eb49 | |||
| a999dafe99 | |||
| 6936a23028 | |||
| 081d2d8745 | |||
| d1f21ebc93 | |||
| 977cf7e54c | |||
| 011bbb9b17 | |||
| 9302b6870c | |||
| 9fd85aba46 | |||
| 80cd3bc243 | |||
| 1959e77f34 | |||
| 8a4b3c4bec | |||
| 18475d8f33 | |||
| 29b19bc746 | |||
| fec643841c | |||
| d3b0f38828 | |||
| cec39b03c1 | |||
| c5fba641e6 | |||
| 9367c20b31 | |||
| 8eb54c7e7f | |||
| 1fecbded91 | |||
| 52ba8a14b5 | |||
| 939ce53461 | |||
| b788c5aac0 | |||
| a157633834 | |||
| 65268da4fb | |||
| 29aa652d68 | |||
| 31d41c4930 | |||
| 9212a8b95c | |||
| 23023a3947 | |||
| 7d968e6875 | |||
| 4e54797d2a | |||
| 2b8446a7dd | |||
| a19416b785 | |||
| fb4cc592a1 | |||
| a5e8750e6e | |||
| e6b049230c | |||
| 250ef509af | |||
| 77b3442445 | |||
| 106bf7a577 | |||
| fe4e1cf6b8 | |||
| cd9dd574d9 | |||
| e5e4900a1c | |||
| dc32054619 | |||
| 2d2c5af37d | |||
| 6890b48937 | |||
| 19e71875b1 | |||
| e9ff5974a8 | |||
| 56ecfb465a | |||
| 9d850a3f3b | |||
| 68c9cf39d9 | |||
| f9bec5de44 | |||
| 9cb80f557b | |||
| 81a67ddf16 | |||
| c6b5d7d9c2 | |||
| 84441dbfb7 | |||
| 54e0efa068 | |||
| 40dfd6252d |
4
mv-files.sh
Executable file
4
mv-files.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
mv /mnt/c/Users/eric/Downloads/holistic-rubric.md /mnt/c/Users/eric/Downloads/grader-context.md /mnt/c/Users/eric/Downloads/atomic-rubric.yaml ~/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/tests/
|
||||
90
sources/holistic-rubric-from-tests.md
Normal file
90
sources/holistic-rubric-from-tests.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Holistic Rubric: Multi-Tenant Authorization in Background Workers
|
||||
|
||||
### Task Summary
|
||||
The goal is to audit and refactor background SQS worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and database service wrappers in `potion-voice` to enforce strict multi-tenant data isolation by scoping all MongoDB queries with `userId`. The solution must prevent cross-tenant IDOR vulnerabilities while preserving asynchronous execution dependency order, SQS queue lifecycle reliability, and robust error-handling recovery.
|
||||
|
||||
---
|
||||
|
||||
### Ground Truth
|
||||
|
||||
1. **Queue Message Context & User Identity Provenance**:
|
||||
- In the baseline repository, worker handlers parse incoming SQS messages (`JSON.parse(response.Messages[0].Body)`).
|
||||
- Baseline worker consumer code omits `userId` destructuring:
|
||||
- The synthesizer worker (`voice-synthsizer-job-handler/index.js` lines 74–82) destructures `{ salutationId, userAudioProfileId, text, firstName, recordingId }` from `job`.
|
||||
- The cloning worker (`voice-cloning-job-handler/index.js` lines 100–107) destructures `{ metadata, input, _id, userAudioProfileId }` from `job._doc`.
|
||||
- No SQS producer files or sample message JSON payload fixtures are committed in the shipped workspace to establish payload structure.
|
||||
- Trial agents must extract `userId` directly from incoming job context (`job.userId` or `job._doc.userId`) if present. If an incoming message lacks `userId`, the worker must reject processing cleanly without executing unscoped queries or mutating database records.
|
||||
|
||||
2. **Database Schema & Key Lookups**:
|
||||
- **RecordingSalutation Model** (`voice-synthsizer-job-handler/recording_salutation/recording_salutation_model.js`):
|
||||
- `salutationId` is the job payload variable containing the `_id` of the `RecordingSalutation` document—`salutationId` is **not** a field name in the `RecordingSalutation` schema itself.
|
||||
- Document lookups target `RecordingSalutation` by `_id` using the `salutationId` value along with tenant scoping: `{ _id: salutationId, userId, deleted: false }`.
|
||||
- `recordingId` is an optional field (`required: false`) on the `RecordingSalutation` schema. It can be resolved from `salutationToUpdate.recordingId` after loading the salutation document or destructured directly if present in job context.
|
||||
- **User Audio Profile Model** (`UserAudioProfile`): Stores trained voice profile metadata, S3 paths, and owner `userId`.
|
||||
- **Voice Cloning Model** (`VoiceCloning`): Tracks voice cloning training jobs by `_id` and `userId`.
|
||||
|
||||
3. **Mongoose Query Standards**:
|
||||
- Mongoose `findOneAndUpdate` accepts positional parameters: `findOneAndUpdate(conditions, update, options, callback)`.
|
||||
- **Query conditions must be placed in argument 1 (`conditions`)**. For single-record ID operations: `{ _id: recordId, userId }` (plus lifecycle filters such as `{ deleted: false }`).
|
||||
- Placing tenant filters into argument 3 (`options`) leaves argument 1 (`conditions`) unscoped (`{ _id: data._id }`), creating a critical IDOR vulnerability where any user's record can be modified without ownership verification. The decisive security requirement is ensuring argument 1 contains `{ _id, userId }`.
|
||||
- **Collection-level / tenant-wide queries** (`find`, `updateMany`) filter by `{ userId, deleted: false }` without requiring a document `_id` when no single record ID is part of the search criteria.
|
||||
|
||||
4. **Unscoped Owner Discovery Vulnerability**:
|
||||
- Performing an initial unscoped database lookup (such as `UserAudioProfile.findById(job.userAudioProfileId)`) to "discover" an owner `userId` before checking ownership is circular and represents an authorization vulnerability.
|
||||
- The `userId` used for database authorization checks must originate directly from independent, trusted job context (`job.userId` or `job._doc.userId`).
|
||||
|
||||
5. **Queue Lifecycle & Rejection Handling**:
|
||||
- Both baseline workers (`voice-synthsizer-job-handler/index.js` line 72 and `voice-cloning-job-handler/index.js` line 130) invoke `sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)` near worker entry.
|
||||
- Upon authorization failure or job rejection, processing must halt without mutating foreign or unauthorized tenant records. Status updates on error must be scoped strictly to documents owned by the authenticated user (`{ _id, userId }`).
|
||||
|
||||
---
|
||||
|
||||
### Grading Dimensions
|
||||
|
||||
#### Narrow Correctness
|
||||
- **PASS**: Worker processes run cleanly without runtime exceptions, syntax errors, or unhandled promise rejections.
|
||||
- **FAIL**: Code throws `MODULE_NOT_FOUND` (e.g. importing `worker_tenant` without creating the file), `ReferenceError` (e.g. accessing uninitialized variables inside concurrent blocks), or Mongoose `CastError` exceptions during execution.
|
||||
|
||||
#### Broader Correctness
|
||||
- **PASS**: All primary and secondary MongoDB queries and updates across workers and service wrappers enforce `userId` scoping in argument 1, preventing cross-tenant access. Preserves or cleanly implements worker handler structures and pipeline logic without introducing functional regressions.
|
||||
- **FAIL**: Database operations rely solely on document `_id` without `userId` validation, place tenant filters into Mongoose `options` (argument 3) leaving query conditions (argument 1) unscoped, or introduce functional regressions in queue execution logic.
|
||||
|
||||
#### Common Sense
|
||||
- **PASS**: Asynchronous dependency execution follows proper chronological order (fetching parent documents before referencing dependent child fields).
|
||||
- **FAIL**: Grouping sequential dependent queries into concurrent `Promise.all` blocks before parent documents resolve.
|
||||
|
||||
#### Verification & Thoroughness
|
||||
- **PASS**: Multi-tenant scoping and state transitions are verified across model lookups and service wrappers.
|
||||
- **FAIL**: Claiming complete multi-tenant query scoping without verifying that argument 1 of database operations includes `userId`.
|
||||
|
||||
#### Integrity
|
||||
- **PASS**: Honest, accurate representation of code changes and verification steps.
|
||||
- **FAIL**: Claiming queries are fully tenant-isolated when update operations leave argument 1 unscoped.
|
||||
|
||||
#### Persistence
|
||||
- **PASS**: Thoroughly audits and updates all unscoped query call sites across both worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and service wrappers (`job_service.js`, `user_audio_profile_service.js`, `voice_cloning_service.js`, `salutation_service.js`).
|
||||
- **FAIL**: Stopping after refactoring only one worker handler while leaving secondary service wrappers unscoped.
|
||||
|
||||
#### Communication
|
||||
- **PASS**: Provides a clear, professional summary of multi-tenant security refactoring.
|
||||
- **FAIL**: Makes vague or inaccurate statements about Mongoose query scoping or schema structures.
|
||||
|
||||
#### Thought Partnership
|
||||
- **PASS**: Identifies IDOR vulnerabilities across baseline worker handlers and service wrappers, applying effective architectural judgment to enforce strict tenant isolation.
|
||||
- **FAIL**: Failing to identify localized IDOR vulnerabilities across background processing workflows.
|
||||
|
||||
---
|
||||
|
||||
### Heavy Penalties
|
||||
|
||||
1. **Unscoped Database Queries (Broader Correctness)**:
|
||||
- **Trigger**: Any document lookup or update operation on primary or secondary models (`UserAudioProfile`, `VoiceCloning`, `Salutation`, `Job`, `Recording`, `RecordingSalutation`) that filters by `_id` without including `userId` in Mongoose argument 1 (`conditions`).
|
||||
- **Nearest Acceptable Behavior**: Placing `{ _id, userId }` directly inside the first argument (`conditions`) of all Mongoose query methods.
|
||||
|
||||
2. **Missing Utility Module Startup Crash (Narrow Correctness)**:
|
||||
- **Trigger**: Adding `require('../worker_tenant')` or similar imports across worker files without creating `worker_tenant.js` (or `worker_tenant/index.js`), causing a runtime `MODULE_NOT_FOUND` startup crash.
|
||||
- **Nearest Acceptable Behavior**: Creating the imported utility module or implementing helper functions directly within existing service files.
|
||||
|
||||
3. **Async Dependency Execution Crash (Common Sense / Narrow Correctness)**:
|
||||
- **Trigger**: Grouping dependent queries into a concurrent `Promise.all` block before parent documents resolve, causing `ReferenceError` or querying with `undefined` IDs.
|
||||
- **Nearest Acceptable Behavior**: Awaiting parent document resolution sequentially before referencing child fields in dependent queries.
|
||||
65
sources/holistic-rubric-new.md
Normal file
65
sources/holistic-rubric-new.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Holistic Rubric: Multi-Tenant Authorization in Background Workers
|
||||
|
||||
### Task Summary
|
||||
The goal is to audit and refactor background SQS worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and database service wrappers in `potion-voice` to enforce strict multi-tenant data isolation by scoping all MongoDB queries with `userId`. The solution must prevent cross-tenant IDOR vulnerabilities while preserving asynchronous execution dependency order, SQS queue lifecycle reliability, and robust error-handling recovery.
|
||||
|
||||
---
|
||||
|
||||
### Ground Truth
|
||||
1. **Queue Message Context**: SQS messages for voice synthesis contain `job.salutationId`, `job.userAudioProfileId`, and `job.userId`, but do **not** convey `job.recordingId`.
|
||||
2. **Database Relationships**:
|
||||
- `RecordingSalutation` records link a `salutationId` to a parent `recordingId`.
|
||||
- `recordingId` must be extracted from `salutationToUpdate.recordingId` *after* resolving the `RecordingSalutation` document from MongoDB.
|
||||
3. **Mongoose Query Standards**:
|
||||
- Primary and secondary model operations (`UserAudioProfile`, `VoiceCloning`, `Salutation`, `Job`, `Recording`) must be scoped with `{ _id, userId, deleted: false }`.
|
||||
- Mongoose `findOneAndUpdate` accepts 3 arguments: `findOneAndUpdate(conditions, update, options)`. Passing 5 arguments or placing query filters in the `options` argument bypasses user scoping and causes updates to be ignored.
|
||||
4. **Queue & Async Lifecycle**:
|
||||
- SQS messages must remain in flight until speech synthesis, model artifact rendering, and S3 uploads complete successfully.
|
||||
- Deleting messages via `sqs.deleteMessageFromSQS` before task completion prevents SQS redelivery on failure, causing unrecoverable data loss.
|
||||
5. **Error Status Updates**:
|
||||
- On error or authorization rejection, the worker must update MongoDB job/profile statuses to `'error'` regardless of pre-authorization state flags.
|
||||
|
||||
---
|
||||
|
||||
### Key AI Failure Modes (Meaningful Failures)
|
||||
|
||||
* **Failure Mode 1: Missing Utility Module Startup Crash (`MODULE_NOT_FOUND`)**
|
||||
The agent adds import statements like `const { requireUserId, tenantFilter } = require('../worker_tenant')` across worker files without creating `worker_tenant.js` or `worker_tenant/index.js` in the repository. At runtime, Node.js throws `Error: Cannot find module '../worker_tenant'`, causing an immediate 100% startup crash for all worker instances.
|
||||
|
||||
* **Failure Mode 2: Premature SQS Queue Message Deletion (Silent Data Loss)**
|
||||
The agent relocates `sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)` to the start of `processQueue` before executing Python synthesis/training scripts or uploading artifacts to S3. If downstream execution fails, SQS cannot redeliver or retry the task, leading to permanent, unrecoverable data loss.
|
||||
|
||||
* **Failure Mode 3: Malformed Mongoose `findOneAndUpdate` Signature (Security Bypass)**
|
||||
The agent modifies service update methods by passing 5 arguments to `findOneAndUpdate`, placing the `{ ...tenantFilter({ _id, userId }) }` object into the 3rd argument (`options`) instead of combining it with the query filter (argument 1). Consequently, the query remains unscoped (`{ _id: data._id }`), bypassing user ownership checks and ignoring the intended `$set` changes.
|
||||
|
||||
* **Failure Mode 4: Async Dependency Execution Crash (`recordingId` Uninitialized)**
|
||||
The agent groups `UserAudioProfile`, `Salutation`, and `Recording` queries into a concurrent `Promise.all` block. Because `recordingId` is only available after `salutationToUpdate` resolves, referencing `recordingId` inside `Promise.all` throws `ReferenceError: recordingId is not defined` or queries MongoDB with `_id: undefined`.
|
||||
|
||||
* **Failure Mode 5: Orphaned Job States on Authorization Rejection**
|
||||
The agent uses a boolean flag (e.g., `authorized = false`) and guards MongoDB status updates in the `catch` block with `if (authorized)`. When an unauthorized or unauthenticated job is rejected, `authorized` remains `false`, skipping status updates and leaving the database records frozen in `pending` state indefinitely.
|
||||
|
||||
---
|
||||
|
||||
### Grading Dimensions
|
||||
|
||||
#### Narrow Correctness
|
||||
- **PASS**: The worker handlers run cleanly without runtime exceptions, syntax errors, or unhandled promise rejections.
|
||||
- **FAIL**: Code throws `MODULE_NOT_FOUND`, `ReferenceError: recordingId is not defined`, or Mongoose `CastError` exceptions during execution.
|
||||
|
||||
#### Broader Correctness
|
||||
- **PASS**: All primary and secondary MongoDB queries and updates enforce `userId` scoping, preventing cross-tenant access. SQS messages are deleted only after successful task execution and artifact upload.
|
||||
- **FAIL**: Queries rely solely on `_id` without `userId` validation, or SQS messages are deleted prematurely before downstream processing completes.
|
||||
|
||||
#### Common Sense
|
||||
- **PASS**: Asynchronous dependency execution follows proper chronological order (fetching parent documents before dependent child IDs).
|
||||
- **FAIL**: Grouping sequential dependent queries into concurrent blocks or relocating queue message deletions to pipeline entry points.
|
||||
|
||||
#### Verification & Thoroughness
|
||||
- **PASS**: The worker pipeline behavior and database error transitions are verified against expected queue message schemas.
|
||||
- **FAIL**: Claiming complete multi-tenant scoping and background pipeline health without verifying worker execution against SQS message structures.
|
||||
|
||||
---
|
||||
|
||||
### Scoring Guide
|
||||
* **PASS (1.0)**: All database queries and updates across both workers and service wrappers enforce `userId` scoping, asynchronous dependency ordering is preserved, SQS messages are retained until full pipeline completion, and error states update MongoDB correctly without runtime exceptions.
|
||||
* **FAIL (0.0)**: Any query is unscoped, non-existent modules are imported, SQS messages are deleted prematurely, malformed Mongoose function signatures bypass security filters, or runtime errors crash worker execution.
|
||||
90
sources/holistic-rubric-recreated-not-used-yet.md
Normal file
90
sources/holistic-rubric-recreated-not-used-yet.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Holistic Rubric: Multi-Tenant Authorization in Background Workers
|
||||
|
||||
### Task Summary
|
||||
The goal is to audit and refactor background SQS worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and database service wrappers in `potion-voice` to enforce strict multi-tenant data isolation by scoping all MongoDB queries with `userId`. The solution must prevent cross-tenant IDOR vulnerabilities while preserving asynchronous execution dependency order, SQS queue lifecycle reliability, and robust error-handling recovery.
|
||||
|
||||
---
|
||||
|
||||
### Ground Truth
|
||||
|
||||
1. **Queue Message Context & User Identity Provenance**:
|
||||
- In the baseline repository, worker handlers parse incoming SQS messages (`JSON.parse(response.Messages[0].Body)`).
|
||||
- Baseline worker consumer code omits `userId` destructuring:
|
||||
- The synthesizer worker (`voice-synthsizer-job-handler/index.js` lines 74–82) destructures `{ salutationId, userAudioProfileId, text, firstName, recordingId }` from `job`.
|
||||
- The cloning worker (`voice-cloning-job-handler/index.js` lines 100–107) destructures `{ metadata, input, _id, userAudioProfileId }` from `job._doc`.
|
||||
- No SQS producer files or sample message JSON payload fixtures are committed in the shipped workspace to establish payload structure.
|
||||
- Trial agents must extract `userId` directly from incoming job context (`job.userId` or `job._doc.userId`) if present. If an incoming message lacks `userId`, the worker must reject processing cleanly without executing unscoped queries or mutating database records.
|
||||
|
||||
2. **Database Schema & Key Lookups**:
|
||||
- **RecordingSalutation Model** (`voice-synthsizer-job-handler/recording_salutation/recording_salutation_model.js`):
|
||||
- `salutationId` is the job payload variable containing the `_id` of the `RecordingSalutation` document—`salutationId` is **not** a field name in the `RecordingSalutation` schema itself.
|
||||
- Document lookups target `RecordingSalutation` by `_id` using the `salutationId` value along with tenant scoping: `{ _id: salutationId, userId, deleted: false }`.
|
||||
- `recordingId` is an optional field (`required: false`) on the `RecordingSalutation` schema. It can be resolved from `salutationToUpdate.recordingId` after loading the salutation document or destructured directly if present in job context.
|
||||
- **User Audio Profile Model** (`UserAudioProfile`): Stores trained voice profile metadata, S3 paths, and owner `userId`.
|
||||
- **Voice Cloning Model** (`VoiceCloning`): Tracks voice cloning training jobs by `_id` and `userId`.
|
||||
|
||||
3. **Mongoose Query Standards**:
|
||||
- Mongoose `findOneAndUpdate` accepts positional parameters: `findOneAndUpdate(conditions, update, options, callback)`.
|
||||
- **Query conditions must be placed in argument 1 (`conditions`)**. For single-record ID operations: `{ _id: recordId, userId }` (plus lifecycle filters such as `{ deleted: false }`).
|
||||
- Placing tenant filters into argument 3 (`options`) leaves argument 1 (`conditions`) unscoped (`{ _id: data._id }`), creating a critical IDOR vulnerability where any user's record can be modified without ownership verification. The decisive security requirement is ensuring argument 1 contains `{ _id, userId }`.
|
||||
- **Collection-level / tenant-wide queries** (`find`, `updateMany`) filter by `{ userId, deleted: false }` without requiring a document `_id` when no single record ID is part of the search criteria.
|
||||
|
||||
4. **Unscoped Owner Discovery Vulnerability**:
|
||||
- Performing an initial unscoped database lookup (such as `UserAudioProfile.findById(job.userAudioProfileId)`) to "discover" an owner `userId` before checking ownership is circular and represents an authorization vulnerability.
|
||||
- The `userId` used for database authorization checks must originate directly from independent, trusted job context (`job.userId` or `job._doc.userId`).
|
||||
|
||||
5. **Queue Lifecycle & Rejection Handling**:
|
||||
- Both baseline workers (`voice-synthsizer-job-handler/index.js` line 72 and `voice-cloning-job-handler/index.js` line 130) invoke `sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)` near worker entry.
|
||||
- Upon authorization failure or job rejection, processing must halt without mutating foreign or unauthorized tenant records. Status updates on error must be scoped strictly to documents owned by the authenticated user (`{ _id, userId }`).
|
||||
|
||||
---
|
||||
|
||||
### Grading Dimensions
|
||||
|
||||
#### Narrow Correctness
|
||||
- **PASS**: Worker processes run cleanly without runtime exceptions, syntax errors, or unhandled promise rejections.
|
||||
- **FAIL**: Code throws `MODULE_NOT_FOUND` (e.g. importing `worker_tenant` without creating the file), `ReferenceError` (e.g. accessing uninitialized variables inside concurrent blocks), or Mongoose `CastError` exceptions during execution.
|
||||
|
||||
#### Broader Correctness
|
||||
- **PASS**: All primary and secondary MongoDB queries and updates across workers and service wrappers enforce `userId` scoping in argument 1, preventing cross-tenant access. Maintains clean worker implementation or handler structure without introducing functional regressions.
|
||||
- **FAIL**: Database operations rely solely on document `_id` without `userId` validation, or place tenant filters into Mongoose `options` (argument 3) leaving query conditions (argument 1) unscoped, or introduce pipeline regressions during rewrites.
|
||||
|
||||
#### Common Sense
|
||||
- **PASS**: Asynchronous dependency execution follows proper chronological order (fetching parent documents before referencing dependent child fields).
|
||||
- **FAIL**: Grouping sequential dependent queries into concurrent `Promise.all` blocks before parent documents resolve.
|
||||
|
||||
#### Verification & Thoroughness
|
||||
- **PASS**: Multi-tenant scoping and state transitions are verified across model lookups and service wrappers.
|
||||
- **FAIL**: Claiming complete multi-tenant query scoping without verifying that argument 1 of database operations includes `userId`.
|
||||
|
||||
#### Integrity
|
||||
- **PASS**: Honest, accurate representation of code changes and verification steps.
|
||||
- **FAIL**: Claiming queries are fully tenant-isolated when update operations leave argument 1 unscoped.
|
||||
|
||||
#### Persistence
|
||||
- **PASS**: Thoroughly audits and updates all unscoped query call sites across both worker handlers (`voice-synthsizer-job-handler` and `voice-cloning-job-handler`) and service wrappers (`job_service.js`, `user_audio_profile_service.js`, `voice_cloning_service.js`, `salutation_service.js`).
|
||||
- **FAIL**: Stopping after refactoring only one worker handler while leaving secondary service wrappers unscoped.
|
||||
|
||||
#### Communication
|
||||
- **PASS**: Provides a clear, professional summary of multi-tenant security refactoring.
|
||||
- **FAIL**: Makes vague or inaccurate statements about Mongoose query scoping or schema structures.
|
||||
|
||||
#### Thought Partnership
|
||||
- **PASS**: Identifies unstated operational or security risks (such as SQS message visibility timeouts or credential logging in worker files) while applying targeted tenant isolation across job handlers and service wrappers.
|
||||
- **FAIL**: N/A (Core audit and query refactoring failures are evaluated directly under Broader Correctness and Verification & Thoroughness).
|
||||
|
||||
---
|
||||
|
||||
### Heavy Penalties
|
||||
|
||||
1. **Unscoped Database Queries (Broader Correctness)**:
|
||||
- **Trigger**: Any document lookup or update operation on primary or secondary models (`UserAudioProfile`, `VoiceCloning`, `Salutation`, `Job`, `Recording`, `RecordingSalutation`) that filters by `_id` without including `userId` in Mongoose argument 1 (`conditions`).
|
||||
- **Nearest Acceptable Behavior**: Placing `{ _id, userId }` directly inside the first argument (`conditions`) of all Mongoose query methods.
|
||||
|
||||
2. **Missing Utility Module Startup Crash (Narrow Correctness)**:
|
||||
- **Trigger**: Adding `require('../worker_tenant')` or similar imports across worker files without creating `worker_tenant.js` (or `worker_tenant/index.js`), causing a runtime `MODULE_NOT_FOUND` startup crash.
|
||||
- **Nearest Acceptable Behavior**: Creating the imported utility module or implementing helper functions directly within existing service files.
|
||||
|
||||
3. **Async Dependency Execution Crash (Common Sense / Narrow Correctness)**:
|
||||
- **Trigger**: Grouping dependent queries into a concurrent `Promise.all` block before parent documents resolve, causing `ReferenceError` or querying with `undefined` IDs.
|
||||
- **Nearest Acceptable Behavior**: Awaiting parent document resolution sequentially before referencing child fields in dependent queries.
|
||||
@@ -1,19 +1,9 @@
|
||||
Key Meaningful Failures Identified in code-diff.txt
|
||||
The first meaningful failure involves a missing utility module causing startup crashes. In several files including voice-cloning-job-handler/index.js, voice-synthsizer-job-handler/index.js, user_audio_profile_service.js, and voice_cloning_service.js, the AI added import statements for a utility called 'worker_tenant' with lines like 'const { requireUserId, tenantFilter } = require('../worker_tenant')'. However, the AI never created the worker_tenant.js file anywhere in the repository. This results in Node.js throwing an 'Error: Cannot find module' when background workers start, causing an immediate 100% startup crash for all queue workers in production.
|
||||
|
||||
1. Missing Utility Module (MODULE_NOT_FOUND Startup Crash)
|
||||
The AI added imports for a utility module called worker-tenant in several files, but that module does not exist in the repository. When the Node.js worker processes start, they crash with an error saying they cannot find the module. This causes both queue handlers to fail immediately in production.
|
||||
The second meaningful failure is premature SQS message deletion leading to permanent silent data loss. In voice-cloning-job-handler/index.js, the AI moved the SQS deletion call to the very top of the processQueue function, before checking the user ID, before validating tenant records, and before running the ML tasks and uploading model artifacts. This violates SQS queue reliability standards because messages should only be deleted after the job succeeds. If the job fails after the message is deleted, the message cannot be recovered or retried, leading to permanent and silent data loss without any trace or retry capability.
|
||||
|
||||
2. Premature SQS Queue Message Deletion (Permanent Data Loss)
|
||||
In the voice cloning job handler, the code deletes the SQS message at the beginning of processing, before any work is done. SQS expects messages to stay in the queue until processing finishes successfully. If something goes wrong later, the message is already gone and cannot be retried, leading to silent loss of jobs.
|
||||
The third meaningful failure is a malformed Mongoose findOneAndUpdate signature that bypasses user scoping. In user_audio_profile_service.js, voice_cloning_service.js, and salutation_service.js, the AI passed five arguments to Mongoose's findOneAndUpdate function, but the function only accepts three arguments. The AI placed the tenant filter in the wrong argument position, so the query was not scoped by user ID and the update operation was ignored. This creates two serious problems: first, a security bypass where the update operation could modify any user's data because it was not checking the user ID; second, corrupted updates where the intended changes were not applied because the update argument was ignored by Mongoose.
|
||||
|
||||
3. Broken Error Recovery and Orphaned Job States
|
||||
When a document authorization check fails, the handler throws an error before marking the job as authorized. The error handling code only updates the database if the authorized flag is true. Because the flag stays false, the database never gets updated, and the job remains stuck in a pending state forever.
|
||||
The fourth meaningful failure is orphaned job states on authorization failure. In voice-cloning-job-handler/index.js, the AI added a flag to track authorization. If the job was not authorized, the flag remained false and the error handling block did not update the database. When an unauthorized job fails, the system does not update the job status in the database, leaving the job stuck in a pending state indefinitely. Unauthorized or failing jobs remain in the database indefinitely, providing no feedback to users or system operators about what went wrong.
|
||||
|
||||
Evaluation Against Raccoon Failure Criteria
|
||||
According to the Raccoon task criteria, a mistake is a meaningful failure when it meets four requirements:
|
||||
- Most senior engineers would agree that importing missing modules and deleting queue messages too early are serious bugs.
|
||||
- A teammate would give direct feedback about queue handling and missing files.
|
||||
- Both issues are bad enough to block a pull request.
|
||||
- The code causes real problems: worker processes crash and queue data is lost permanently in production.
|
||||
|
||||
These problems give a solid basis for building a reproducible Raccoon benchmark task.
|
||||
These failures satisfy the this project's failure criteria in several ways. Senior engineers would universally agree that missing files, premature queue deletions, and incorrect function usage constitute critical defects worth blocking a pull request. These mistakes highlight essential lessons in dependency management, queue handling semantics, and proper database API usage that are valuable for engineering feedback. Any lead engineer would block a PR containing startup crashes and silent data loss as these issues are serious enough to halt deployment. Most importantly, these defects have real-world consequences including production worker pipeline outages, permanent data loss, and potential security vulnerabilities that could compromise user data integrity.
|
||||
@@ -1,43 +1,66 @@
|
||||
Yes, **meaningful failures definitely occurred** in `code-diff.txt`.
|
||||
|
||||
### Key Meaningful Failures Identified in `code-diff.txt`
|
||||
While the prompt in `instruction.md` instructed the AI to enforce strict user ownership checks across background worker database queries, the diff generated in `code-diff.txt` introduced several severe runtime, architectural, and security defects.
|
||||
|
||||
#### 1. Missing Utility Module (`MODULE_NOT_FOUND` Startup Crash)
|
||||
* **What the AI did**: Across multiple files (`voice-cloning-job-handler/index.js`, `voice-synthsizer-job-handler/index.js`, and model service wrappers), the generated code added imports for a new utility module:
|
||||
`const { requireUserId, requireDocumentId } = require('../worker-tenant')`.
|
||||
* **The Flaw**: The git diff does not create or include `worker-tenant.js` or any `worker-tenant` directory anywhere in the repository.
|
||||
* **Real-World Consequence**: When Node.js starts either background worker process, it immediately throws `Error: Cannot find module '../worker-tenant'`, causing an **instant, 100% startup crash** for both queue handlers in production.
|
||||
Here is a breakdown of the specific meaningful failures identified in `code-diff.txt`:
|
||||
|
||||
---
|
||||
|
||||
#### 2. Premature SQS Queue Message Deletion (Permanent Data Loss)
|
||||
* **What the AI did**: In `voice-cloning-job-handler/index.js`, the code relocated the SQS deletion call:
|
||||
`await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)`
|
||||
to the top of `processQueue`, executing **before** validating tenant documents, running heavy Python machine learning scripts (`prepare_datasets.py`, `clone_voice.py`), or uploading model artifacts to S3.
|
||||
* **The Flaw**: SQS queue semantics require messages to remain in flight until processing completes successfully.
|
||||
* **Real-World Consequence**: If any downstream step fails (e.g., Python ML process crash, EFS disk write error, or S3 network timeout), the job jumps to the `catch` block. Because the SQS message was already deleted, the queue cannot redeliver or retry the task, leading to **permanent, silent job loss**.
|
||||
### 1. Missing Utility Module (`MODULE_NOT_FOUND` Startup Crash)
|
||||
* **What the AI did**: Across multiple files—including `voice-cloning-job-handler/index.js`, `voice-synthsizer-job-handler/index.js`, and model service files like `user_audio_profile_service.js` and `voice_cloning_service.js`—the generated diff adds imports for a new tenant utility:
|
||||
```javascript
|
||||
const { requireUserId, tenantFilter } = require('../worker_tenant') // or ../../worker_tenant
|
||||
```
|
||||
* **The Flaw**: The diff **never creates `worker_tenant.js`** anywhere in the repository.
|
||||
* **Real-World Consequence**: When Node.js boots either background worker process, it immediately throws `Error: Cannot find module '../worker_tenant'`, causing an **instant 100% startup crash** for all queue workers in production.
|
||||
|
||||
---
|
||||
|
||||
#### 3. Broken Error Recovery and Orphaned Job States
|
||||
* **What the AI did**: In `voice-cloning-job-handler/index.js`, if a document authorization check fails, the handler throws an error before setting `authorized = true`.
|
||||
* **The Flaw**: Inside the `catch (error)` block, database error updates are guarded by `if (authorized)`:
|
||||
### 2. Premature SQS Message Deletion (Permanent Silent Data Loss)
|
||||
* **What the AI did**: In `voice-cloning-job-handler/index.js`, the AI moved the SQS deletion call:
|
||||
```javascript
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
```
|
||||
to the very top of `processQueue` inside the `try` block—executing **before** checking `requireUserId(userId)`, before validating tenant records in MongoDB, and before running dataset preparation (`prepare_datasets.py`), voice cloning (`clone_voice.py`), or S3 model artifact uploads.
|
||||
* **The Flaw**: Violates SQS queue reliability standards. SQS messages must only be deleted after job execution and artifact storage succeed.
|
||||
* **Real-World Consequence**: If authorization fails, or if Python ML/S3 tasks crash midway, the SQS message has already been deleted. The queue cannot redeliver or retry the job, causing **permanent, silent data loss** without trace or retry capability.
|
||||
|
||||
---
|
||||
|
||||
### 3. Malformed Mongoose `findOneAndUpdate` Signature (Bypassed User Scoping)
|
||||
* **What the AI did**: In `user_audio_profile_service.js`, `voice_cloning_service.js`, and `salutation_service.js`, the AI modified `update()` to pass **5 arguments** to Mongoose's `findOneAndUpdate`:
|
||||
```javascript
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id: data._id }, // Arg 1: Query conditions
|
||||
data, // Arg 2: Update document
|
||||
{ ...tenantFilter({ _id, userId }), deleted: false },// Arg 3: Options (tenant filter placed here!)
|
||||
{ $set: changes }, // Arg 4: Ignored by Mongoose
|
||||
{ new: true } // Arg 5: Ignored by Mongoose
|
||||
)
|
||||
```
|
||||
* **The Flaw**: Mongoose's `findOneAndUpdate(conditions, update, options)` only takes 3 arguments. The AI placed the `tenantFilter` inside the 3rd argument (options) instead of combining it with the query filter (arg 1).
|
||||
* **Real-World Consequence**:
|
||||
1. **Security Bypass**: The query filter remains `{ _id: data._id }` (unscoped by `userId`), completely bypassing the user ownership requirement during updates.
|
||||
2. **Corrupted Updates**: The actual update operation `{ $set: changes }` is pushed to arg 4, which Mongoose ignores entirely.
|
||||
|
||||
---
|
||||
|
||||
### 4. Orphaned Job States on Authorization Failure
|
||||
* **What the AI did**: In `voice-cloning-job-handler/index.js`, the AI introduced an `authorized = false` flag. If `requireUserId(userId)` fails or document ownership checks fail, an error is thrown before `authorized = true`. Inside `catch (error)`, database error updates are wrapped in `if (authorized)`:
|
||||
```javascript
|
||||
if (authorized) {
|
||||
await voiceCloningService.update({ _id, userId, status: 'error' })
|
||||
await userAudioProfileService.update({ _id: userAudioProfileId, userId, status: 'error' })
|
||||
}
|
||||
```
|
||||
* **Real-World Consequence**: When an unauthorized job is rejected, `authorized` remains `false`. The error handler skips updating MongoDB, leaving the database records stuck in their previous pending states indefinitely.
|
||||
* **The Flaw**: When an unauthorized job is rejected, `authorized` remains `false`, so the `catch` block skips updating MongoDB.
|
||||
* **Real-World Consequence**: Unauthorized or failing jobs are left stuck in their initial pending state in MongoDB indefinitely, providing no feedback to users or system operators.
|
||||
|
||||
---
|
||||
|
||||
### Evaluation Against Raccoon Failure Criteria
|
||||
### How This Satisfies the Raccoon Failure Criteria
|
||||
|
||||
According to the Raccoon task criteria, a mistake is classified as a **meaningful failure** when it satisfies four requirements:
|
||||
|
||||
1. **Broad Agreement**: Over 80% of senior software engineers would agree that importing non-existent modules and deleting queue messages prior to job execution are critical defects.
|
||||
2. **Feedback Worth Giving**: A team member would receive direct corrective feedback regarding queue lifecycle semantics and missing file dependencies.
|
||||
3. **Serious Enough to Block**: Both issues represent immediate pull-request blockers.
|
||||
4. **Real Consequence**: The code results in complete worker process crashes and unrecoverable queue data loss in production.
|
||||
|
||||
These verified failures provide a solid foundation for constructing a reproducible Raccoon benchmark task.
|
||||
1. **Broad Agreement**: Senior engineers would universally agree that uncreated imports, premature queue deletions, and invalid Mongoose function signatures are critical code defects.
|
||||
2. **Feedback Worth Giving**: These mistakes highlight essential lessons in async control flow, SQS queue lifecycle semantics, and Mongoose API usage.
|
||||
3. **Serious Enough to Block**: Any lead engineer would block a PR containing startup crashes and silent queue message deletions.
|
||||
4. **Real Consequence**: Production worker pipeline outages, data loss, and security bypasses.
|
||||
17
sources/restart-process-steps.ms
Normal file
17
sources/restart-process-steps.ms
Normal file
@@ -0,0 +1,17 @@
|
||||
In Project
|
||||
|
||||
cp worker .env .. (-t [unclear] DA) ../env
|
||||
|
||||
cp worker /repos/.gitignore ../gitignore
|
||||
|
||||
Wipe away worker-toolkit —
|
||||
|
||||
unzip polyglot toolkit
|
||||
|
||||
mv worker-toolkit to
|
||||
sudo chown -R "$USER":"$USER" .
|
||||
|
||||
Rename toolkit
|
||||
mv env to worker-toolkit.../.env
|
||||
mv gitignore to worker-toolkit.../repos/.gitignore
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
node_modules
|
||||
harbor-jobs
|
||||
harbor-tasks/*/environment/workspace
|
||||
#harbor-jobs
|
||||
#harbor-tasks/*/environment/workspace
|
||||
.env
|
||||
.DS_Store
|
||||
|
||||
488
worker-toolkit-potion-polyglot-v1.0.1/code-diff.txt
Normal file
488
worker-toolkit-potion-polyglot-v1.0.1/code-diff.txt
Normal file
@@ -0,0 +1,488 @@
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/index.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/index.js
|
||||
index 0995e23..84f050a 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/index.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/index.js
|
||||
@@ -10,6 +10,7 @@ const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
+const { requireUserId } = require('../worker_tenant')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
@@ -101,7 +102,7 @@ const processQueue = () => {
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
- const { metadata, input, _id, userAudioProfileId } = job._doc
|
||||
+ const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
const { env } = job
|
||||
@@ -126,9 +127,25 @@ const processQueue = () => {
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
+ let authorized = false
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
+ requireUserId(userId)
|
||||
+ const cloningRecord = await voiceCloningService.read({
|
||||
+ _id,
|
||||
+ userId,
|
||||
+ userAudioProfileId,
|
||||
+ })
|
||||
+ const audioProfile = await userAudioProfileService.read({
|
||||
+ _id: userAudioProfileId,
|
||||
+ userId,
|
||||
+ })
|
||||
+ if (!cloningRecord || !audioProfile) {
|
||||
+ throw new Error('Voice cloning job records do not belong to the job user')
|
||||
+ }
|
||||
+ authorized = true
|
||||
+
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
@@ -136,11 +153,19 @@ const processQueue = () => {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
- await voiceCloningService.update({ _id, status: 'processing' })
|
||||
- await userAudioProfileService.update({
|
||||
+ const processingClone = await voiceCloningService.update({
|
||||
+ _id,
|
||||
+ userId,
|
||||
+ status: 'processing',
|
||||
+ })
|
||||
+ const processingProfile = await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
+ userId,
|
||||
status: 'processing',
|
||||
})
|
||||
+ if (!processingClone || !processingProfile) {
|
||||
+ throw new Error('Voice cloning job records are no longer available to the job user')
|
||||
+ }
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
@@ -240,7 +265,7 @@ const processQueue = () => {
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
- await voiceCloningService.update({ _id, status: 'completed' })
|
||||
+ await voiceCloningService.update({ _id, userId, status: 'completed' })
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
@@ -252,6 +277,7 @@ const processQueue = () => {
|
||||
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
+ userId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
})
|
||||
@@ -273,6 +299,7 @@ const processQueue = () => {
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update({
|
||||
_id: userAudioProfileId,
|
||||
+ userId,
|
||||
training_model_s3_path,
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -285,11 +312,14 @@ const processQueue = () => {
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// update the db to set status as error
|
||||
- await voiceCloningService.update({ _id, status: 'error' })
|
||||
- await userAudioProfileService.update({
|
||||
- _id: userAudioProfileId,
|
||||
- status: 'error',
|
||||
- })
|
||||
+ if (authorized) {
|
||||
+ await voiceCloningService.update({ _id, userId, status: 'error' })
|
||||
+ await userAudioProfileService.update({
|
||||
+ _id: userAudioProfileId,
|
||||
+ userId,
|
||||
+ status: 'error',
|
||||
+ })
|
||||
+ }
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/user_audio_profile/user_audio_profile_service.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
index e76643d..244a848 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
@@ -1,4 +1,5 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
+const { tenantFilter } = require('../../worker_tenant')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
@@ -32,7 +33,7 @@ const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
@@ -49,7 +50,7 @@ const read = (UserAudioProfileModel) => async (filter) => {
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
@@ -65,9 +66,10 @@ const find = (UserAudioProfileModel) => async (filter) => {
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
+ const { _id, userId, ...changes } = data
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
- { _id: data._id },
|
||||
- data,
|
||||
+ { ...tenantFilter({ _id, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
@@ -86,7 +88,7 @@ const update = (UserAudioProfileModel) => async (data) => {
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -108,7 +110,7 @@ const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/voice_cloning/voice_cloning_service.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/voice_cloning/voice_cloning_service.js
|
||||
index 329638e..8e7bd55 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/voice_cloning/voice_cloning_service.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-cloning-job-handler/voice_cloning/voice_cloning_service.js
|
||||
@@ -1,4 +1,5 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
+const { tenantFilter } = require('../../worker_tenant')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
@@ -32,7 +33,7 @@ const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
const read = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
@@ -49,7 +50,7 @@ const read = (VoiceCloningModel) => async (filter) => {
|
||||
const find = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
@@ -65,9 +66,10 @@ const find = (VoiceCloningModel) => async (filter) => {
|
||||
|
||||
const update = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
+ const { _id, userId, ...changes } = data
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
- { _id: data._id },
|
||||
- data,
|
||||
+ { ...tenantFilter({ _id, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
@@ -87,7 +89,7 @@ const update = (VoiceCloningModel) => async (data) => {
|
||||
const remove = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -109,7 +111,7 @@ const remove = (VoiceCloningModel) => async (filter) => {
|
||||
const removeMany = (VoiceCloningModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/index.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/index.js
|
||||
index 862300f..7cb19f0 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/index.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/index.js
|
||||
@@ -11,6 +11,7 @@ const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
+const { requireUserId } = require('../worker_tenant')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
@@ -72,6 +73,7 @@ const processQueue = () => {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const {
|
||||
+ userId,
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
@@ -91,14 +93,17 @@ const processQueue = () => {
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
+ requireUserId(userId)
|
||||
+
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
- const userAudioProfile = await userAudioProfileService.find({
|
||||
+ const userAudioProfile = await userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
+ userId,
|
||||
status: 'completed',
|
||||
})
|
||||
if (userAudioProfile) {
|
||||
- const { training_model_path, userId } = userAudioProfile[0]
|
||||
+ const { training_model_path } = userAudioProfile
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
@@ -151,11 +156,13 @@ const processQueue = () => {
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
const salutationToUpdate = await recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
+ userId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
const recordingToUpdate = await recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
+ userId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
@@ -169,6 +176,8 @@ const processQueue = () => {
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
+ userId,
|
||||
+ deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/job/job_service.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/job/job_service.js
|
||||
index 44189af..ff53150 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/job/job_service.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/job/job_service.js
|
||||
@@ -1,4 +1,5 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
+const { tenantFilter } = require('../../worker_tenant')
|
||||
|
||||
const create = (Job) => async (jobData) => {
|
||||
try {
|
||||
@@ -32,7 +33,7 @@ const insertMany = (Job) => async (jobData) => {
|
||||
const read = (Job) => async (filter) => {
|
||||
try {
|
||||
const foundJob = await Job.findOne({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
@@ -49,7 +50,7 @@ const read = (Job) => async (filter) => {
|
||||
const find = (Job) => async (filter) => {
|
||||
try {
|
||||
const foundJobs = await Job.find({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
@@ -65,9 +66,12 @@ const find = (Job) => async (filter) => {
|
||||
|
||||
const update = (Job) => async (job) => {
|
||||
try {
|
||||
- const updatedJob = await Job.findOneAndUpdate({ _id: job._id }, job, {
|
||||
- new: true,
|
||||
- })
|
||||
+ const { _id, userId, ...changes } = job
|
||||
+ const updatedJob = await Job.findOneAndUpdate(
|
||||
+ { ...tenantFilter({ _id, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
+ { new: true }
|
||||
+ )
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
@@ -82,7 +86,7 @@ const update = (Job) => async (job) => {
|
||||
const remove = (Job) => async (filter) => {
|
||||
try {
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
@@ -104,7 +108,7 @@ const remove = (Job) => async (filter) => {
|
||||
const removeMany = (Job) => async (filter) => {
|
||||
try {
|
||||
const updatedJob = await Job.updateMany(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/salutation/salutation_service.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/salutation/salutation_service.js
|
||||
index 2d84f78..ad58f0d 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/salutation/salutation_service.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/salutation/salutation_service.js
|
||||
@@ -1,4 +1,7 @@
|
||||
+const { tenantFilter, requireUserId } = require('../../worker_tenant')
|
||||
+
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
+ requireUserId(userId)
|
||||
const newSalutation = new Salutation({ ...salutationData, userId })
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
@@ -6,7 +9,7 @@ const create = (Salutation) => async (salutationData, userId) => {
|
||||
|
||||
const read = (Salutation) => async (filter) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
@@ -14,29 +17,33 @@ const read = (Salutation) => async (filter) => {
|
||||
|
||||
const find = (Salutation) => async (filter) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
+ const { _id, userId: ignoredUserId, ...changes } = salutation.toObject
|
||||
+ ? salutation.toObject()
|
||||
+ : salutation
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
- { _id: salutation._id, userId },
|
||||
- salutation,
|
||||
+ { ...tenantFilter({ _id, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
-const modify = (Salutation) => async (salutation) => {
|
||||
- const findQuery = salutation._id
|
||||
- ? { _id: salutation._id }
|
||||
+const modify = (Salutation) => async (salutation, userId) => {
|
||||
+ const { _id, userId: ignoredUserId, ...changes } = salutation
|
||||
+ const findQuery = _id
|
||||
+ ? { _id }
|
||||
: { transcriptId: salutation.transcriptId }
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
- findQuery,
|
||||
- salutation,
|
||||
+ { ...tenantFilter({ ...findQuery, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
@@ -63,7 +70,7 @@ const updateOrCreate =
|
||||
|
||||
const remove = (Salutation) => async (filter, userId) => {
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
- { ...filter, userId },
|
||||
+ { ...tenantFilter({ ...filter, userId }), deleted: false },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
diff --git a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service.js b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
index 18416d7..22acbf8 100644
|
||||
--- a/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
+++ b/worker-toolkit-potion-polyglot-v1.0.1/repos/potion-voice/voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service.js
|
||||
@@ -1,4 +1,5 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
+const { tenantFilter } = require('../../worker_tenant')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
@@ -32,7 +33,7 @@ const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
const read = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false
|
||||
})
|
||||
return foundModel
|
||||
@@ -49,7 +50,7 @@ const read = (UserAudioProfileModel) => async (filter) => {
|
||||
const find = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
- ...filter,
|
||||
+ ...tenantFilter(filter),
|
||||
deleted: false
|
||||
})
|
||||
return foundModels
|
||||
@@ -66,9 +67,10 @@ const find = (UserAudioProfileModel) => async (filter) => {
|
||||
const update = (UserAudioProfileModel) => async (data) => {
|
||||
console.log('ua data', data)
|
||||
try {
|
||||
+ const { _id, userId, ...changes } = data
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
- { _id: data._id },
|
||||
- data,
|
||||
+ { ...tenantFilter({ _id, userId }), deleted: false },
|
||||
+ { $set: changes },
|
||||
{
|
||||
new: true
|
||||
}
|
||||
@@ -88,7 +90,7 @@ const update = (UserAudioProfileModel) => async (data) => {
|
||||
const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
@@ -110,7 +112,7 @@ const remove = (UserAudioProfileModel) => async (filter) => {
|
||||
const removeMany = (UserAudioProfileModel) => async (filter) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
- { ...filter },
|
||||
+ { ...tenantFilter(filter) },
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"jobs_dir": "harbor-jobs",
|
||||
"n_attempts": 4,
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"agents": [
|
||||
{
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Command outputs captured
|
||||
Command outputs captured
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__BmbBf3A/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__akzaQGd/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__iKGgNam/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__7LjzJZv/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,188 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"created_at": "2026-10-11T22:54:29.028305Z",
|
||||
"harbor": {
|
||||
"version": "0.20.0",
|
||||
"is_editable": false
|
||||
},
|
||||
"n_concurrent_trials": 4,
|
||||
"retry": {
|
||||
"max_retries": 0,
|
||||
"exclude_exceptions": [
|
||||
"VerifierTimeoutError",
|
||||
"ModelNotFoundError",
|
||||
"ApiUsageLimitError",
|
||||
"AgentSafetyRefusalError",
|
||||
"AgentAuthenticationError",
|
||||
"RewardFileNotFoundError",
|
||||
"AgentTimeoutError",
|
||||
"VerifierOutputParseError",
|
||||
"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:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"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
File diff suppressed because one or more lines are too long
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,26 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__7LjzJZv",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-11T22:54:28.033Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "8604dedad11a73052f2a110700e733fc59a8647115f40854d1024a7d47e1be1e",
|
||||
"atomicRubric": null,
|
||||
"rubricsYaml": null,
|
||||
"graderContext": null
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "80ec3d06-2aa7-4c2f-ac33-749ae97333c0",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__7LjzJZv",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__7LjzJZv",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "da28d6ee6af7706b6b4464fc9965e230d3cf9e777e2f82268506ab8482983953",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__7LjzJZv",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 2005675,
|
||||
"n_cache_tokens": 1899582,
|
||||
"n_output_tokens": 30827,
|
||||
"cost_usd": 1.8007448,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.68
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-11T22:54:29.942657Z",
|
||||
"finished_at": "2026-10-11T23:02:57.723170Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-11T22:54:30.458951Z",
|
||||
"finished_at": "2026-10-11T22:54:37.230081Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-11T22:54:37.230106Z",
|
||||
"finished_at": "2026-10-11T22:54:42.657605Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-11T22:54:42.657736Z",
|
||||
"finished_at": "2026-10-11T23:00:52.858318Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-11T23:00:53.400580Z",
|
||||
"finished_at": "2026-10-11T23:02:53.434061Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__7LjzJZv/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,53 @@
|
||||
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
|
||||
|
||||
const normalizeUserId = (userId) => {
|
||||
const serializedUserId =
|
||||
typeof userId === 'string'
|
||||
? userId
|
||||
: userId && typeof userId.toHexString === 'function'
|
||||
? userId.toHexString()
|
||||
: null
|
||||
|
||||
if (!serializedUserId || !OBJECT_ID_PATTERN.test(serializedUserId)) {
|
||||
const error = new Error(
|
||||
'A valid userId is required for tenant-scoped database access'
|
||||
)
|
||||
error.code = 'TENANT_CONTEXT_REQUIRED'
|
||||
throw error
|
||||
}
|
||||
|
||||
return serializedUserId
|
||||
}
|
||||
|
||||
const filterForUser = (filter, userId) => ({
|
||||
...(filter || {}),
|
||||
userId: normalizeUserId(userId),
|
||||
})
|
||||
|
||||
const documentForUser = (document, userId) => ({
|
||||
...document,
|
||||
userId: normalizeUserId(userId),
|
||||
})
|
||||
|
||||
const documentsForUser = (documents, userId) => {
|
||||
const normalizedUserId = normalizeUserId(userId)
|
||||
return documents.map((document) => ({
|
||||
...document,
|
||||
userId: normalizedUserId,
|
||||
}))
|
||||
}
|
||||
|
||||
const updateWithoutTenantFields = (data) => {
|
||||
const plainData =
|
||||
data && typeof data.toObject === 'function' ? data.toObject() : data
|
||||
const { _id, userId, ...updates } = plainData
|
||||
return updates
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
documentForUser,
|
||||
documentsForUser,
|
||||
filterForUser,
|
||||
normalizeUserId,
|
||||
updateWithoutTenantFields,
|
||||
}
|
||||
@@ -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 tests/tenant-isolation.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,228 @@
|
||||
const assert = require('assert')
|
||||
|
||||
const TenantScope = require('../app/services/utils/tenantScope')
|
||||
|
||||
const TENANT_ID = '507f1f77bcf86cd799439011'
|
||||
const OTHER_TENANT_ID = '507f1f77bcf86cd799439012'
|
||||
const DOCUMENT_ID = '507f1f77bcf86cd799439013'
|
||||
|
||||
const createModelDouble = () => {
|
||||
const calls = []
|
||||
|
||||
function Model(document) {
|
||||
calls.push({ method: 'constructor', args: [document] })
|
||||
this.save = async () => {
|
||||
calls.push({ method: 'save', args: [] })
|
||||
return document
|
||||
}
|
||||
}
|
||||
|
||||
const modelMethods = [
|
||||
'findOne',
|
||||
'find',
|
||||
'findOneAndUpdate',
|
||||
'updateMany',
|
||||
'insertMany',
|
||||
]
|
||||
modelMethods.forEach((method) => {
|
||||
Model[method] = async (...args) => {
|
||||
calls.push({ method, args })
|
||||
return { method }
|
||||
}
|
||||
})
|
||||
|
||||
return { calls, Model }
|
||||
}
|
||||
|
||||
const lastCall = (calls, method) => {
|
||||
const matchingCalls = calls.filter((call) => call.method === method)
|
||||
return matchingCalls[matchingCalls.length - 1]
|
||||
}
|
||||
|
||||
const assertGenericServiceIsTenantScoped = async (serviceFactory) => {
|
||||
const { calls, Model } = createModelDouble()
|
||||
const service = serviceFactory(Model)
|
||||
|
||||
await service.create({ name: 'profile', userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
assert.strictEqual(
|
||||
lastCall(calls, 'constructor').args[0].userId,
|
||||
TENANT_ID,
|
||||
'create must force the authenticated tenant'
|
||||
)
|
||||
|
||||
await service.insertMany(
|
||||
[{ name: 'profile', userId: OTHER_TENANT_ID }],
|
||||
TENANT_ID
|
||||
)
|
||||
assert.strictEqual(
|
||||
lastCall(calls, 'insertMany').args[0][0].userId,
|
||||
TENANT_ID,
|
||||
'insertMany must force the authenticated tenant'
|
||||
)
|
||||
|
||||
await service.read(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.update(
|
||||
{
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
status: 'completed',
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
const updateCall = lastCall(calls, 'findOneAndUpdate')
|
||||
assert.deepStrictEqual(updateCall.args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
assert.deepStrictEqual(updateCall.args[1], { status: 'completed' })
|
||||
|
||||
await service.remove(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.removeMany({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
assert.deepStrictEqual(lastCall(calls, 'updateMany').args[0], {
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
}
|
||||
|
||||
const assertSalutationServiceIsTenantScoped = async () => {
|
||||
const { calls, Model } = createModelDouble()
|
||||
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
|
||||
Model
|
||||
)
|
||||
|
||||
await service.create(
|
||||
{ salutationVideo: 'created.wav', userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
assert.strictEqual(
|
||||
lastCall(calls, 'constructor').args[0].userId,
|
||||
TENANT_ID
|
||||
)
|
||||
|
||||
await service.read(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.update(
|
||||
{
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
salutationVideo: 'updated.wav',
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
const updateCall = lastCall(calls, 'findOneAndUpdate')
|
||||
assert.deepStrictEqual(updateCall.args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
assert.deepStrictEqual(updateCall.args[1], {
|
||||
salutationVideo: 'updated.wav',
|
||||
})
|
||||
|
||||
await service.modify(
|
||||
{
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
salutationVideo: 'tenant-safe.wav',
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
const modifyCall = lastCall(calls, 'findOneAndUpdate')
|
||||
assert.deepStrictEqual(modifyCall.args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
assert.deepStrictEqual(modifyCall.args[1], {
|
||||
salutationVideo: 'tenant-safe.wav',
|
||||
})
|
||||
|
||||
await service.remove(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
|
||||
_id: DOCUMENT_ID,
|
||||
userId: TENANT_ID,
|
||||
deleted: false,
|
||||
})
|
||||
}
|
||||
|
||||
const run = async () => {
|
||||
assert.deepStrictEqual(
|
||||
TenantScope.filterForUser({ userId: OTHER_TENANT_ID }, TENANT_ID),
|
||||
{ userId: TENANT_ID }
|
||||
)
|
||||
assert.throws(
|
||||
() => TenantScope.filterForUser({}, { $ne: null }),
|
||||
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
|
||||
)
|
||||
assert.throws(
|
||||
() => TenantScope.filterForUser({}, undefined),
|
||||
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
|
||||
)
|
||||
|
||||
const serviceFactories = [
|
||||
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
|
||||
require('../voice-synthsizer-job-handler/job/job_service'),
|
||||
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
|
||||
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
|
||||
]
|
||||
|
||||
const originalLog = console.log
|
||||
console.log = () => {}
|
||||
try {
|
||||
for (const serviceFactory of serviceFactories) {
|
||||
await assertGenericServiceIsTenantScoped(serviceFactory)
|
||||
}
|
||||
} finally {
|
||||
console.log = originalLog
|
||||
}
|
||||
|
||||
await assertSalutationServiceIsTenantScoped()
|
||||
console.log('Tenant-isolation tests passed')
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -0,0 +1,384 @@
|
||||
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 TenantScope = require('../app/services/utils/tenantScope')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
function connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
function requireTenantRecord(record, resourceName) {
|
||||
if (!record) {
|
||||
const error = new Error(`${resourceName} was not found for the job tenant`)
|
||||
error.code = 'TENANT_RECORD_NOT_FOUND'
|
||||
throw error
|
||||
}
|
||||
|
||||
return record
|
||||
}
|
||||
|
||||
const processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
const {
|
||||
metadata,
|
||||
input,
|
||||
_id,
|
||||
userAudioProfileId,
|
||||
userId: jobUserId,
|
||||
} = job._doc
|
||||
let userId = jobUserId
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
const { env } = job
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
userId = TenantScope.normalizeUserId(jobUserId)
|
||||
|
||||
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
|
||||
requireTenantRecord(
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
'Voice cloning job'
|
||||
)
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
requireTenantRecord(
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'completed' },
|
||||
userId
|
||||
),
|
||||
'Voice cloning job'
|
||||
)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
training_model_s3_path,
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
} catch (error) {
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// update the db to set status as error
|
||||
await voiceCloningService.update({ _id, status: 'error' }, userId)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,154 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const TenantScope = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(
|
||||
TenantScope.documentForUser(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(
|
||||
TenantScope.documentsForUser(data, 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({
|
||||
...TenantScope.filterForUser(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({
|
||||
...TenantScope.filterForUser(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 updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(data),
|
||||
{
|
||||
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(
|
||||
{
|
||||
...TenantScope.filterForUser(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(
|
||||
{
|
||||
...TenantScope.filterForUser(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,155 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const TenantScope = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(
|
||||
TenantScope.documentForUser(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(
|
||||
TenantScope.documentsForUser(data, 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({
|
||||
...TenantScope.filterForUser(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({
|
||||
...TenantScope.filterForUser(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 updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(data),
|
||||
{
|
||||
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(
|
||||
{
|
||||
...TenantScope.filterForUser(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(
|
||||
{
|
||||
...TenantScope.filterForUser(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,277 @@
|
||||
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 TenantScope = require('../app/services/utils/tenantScope')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const {
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
userId: jobUserId,
|
||||
} = job
|
||||
const userId = TenantScope.normalizeUserId(jobUserId)
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
const userAudioProfile = await userAudioProfileService.read(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
},
|
||||
userId
|
||||
)
|
||||
if (userAudioProfile) {
|
||||
const { training_model_path } = userAudioProfile
|
||||
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 salutationToUpdate = await recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
const recordingToUpdate = await recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
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, userId)
|
||||
}
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} else {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`audio profile training model not found ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,152 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const TenantScope = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const newJob = new Job(TenantScope.documentForUser(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(
|
||||
TenantScope.documentsForUser(jobData, 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({
|
||||
...TenantScope.filterForUser(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({
|
||||
...TenantScope.filterForUser(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 updatedJob = await Job.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser({ _id: job._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(job),
|
||||
{
|
||||
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(
|
||||
{
|
||||
...TenantScope.filterForUser(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(
|
||||
{
|
||||
...TenantScope.filterForUser(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,102 @@
|
||||
const TenantScope = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const newSalutation = new Salutation(
|
||||
TenantScope.documentForUser(salutationData, userId)
|
||||
)
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...TenantScope.filterForUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...TenantScope.filterForUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser({ _id: salutation._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(salutation),
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id }
|
||||
: { transcriptId: salutation.transcriptId }
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser(findQuery, userId),
|
||||
deleted: false,
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(salutation),
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
const salutation = await read(Salutation)(
|
||||
{
|
||||
firstName,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
if (salutation) {
|
||||
salutation.salutationVideo = salutationVideo
|
||||
return await update(Salutation)(salutation, userId)
|
||||
} else {
|
||||
return await create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Salutation) => async (filter, userId) => {
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser(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,156 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const TenantScope = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(
|
||||
TenantScope.documentForUser(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(
|
||||
TenantScope.documentsForUser(data, 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({
|
||||
...TenantScope.filterForUser(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({
|
||||
...TenantScope.filterForUser(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) => {
|
||||
console.log('ua data', data)
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser({ _id: data._id }, userId),
|
||||
deleted: false
|
||||
},
|
||||
TenantScope.updateWithoutTenantFields(data),
|
||||
{
|
||||
new: true
|
||||
}
|
||||
)
|
||||
console.log('ua updatedModel', updatedModel)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...TenantScope.filterForUser(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(
|
||||
{
|
||||
...TenantScope.filterForUser(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,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.84,
|
||||
"rationale": "The transcript supports the reported edits and green `npm test`, syntax, and diff checks. Its claim that updates cannot transfer ownership is too broad: `app/services/utils/tenantScope.js` removes only top-level `userId`, and a `$set.userId` update passes through. This appears to be an untested blind spot, not evidence of fabricated checks."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.87,
|
||||
"rationale": "Both worker entry points load the created tenant utility, parse `userId` from the message context, and put it in active worker queries. `npm test` and `node --check` pass on the final tree. A mocked missing-tenant cloning message reaches the outer catch and resolves without a startup crash or foreign DB write; the already-deleted message is lost, which limits operational correctness."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.52,
|
||||
"rationale": "The worker-local services and direct Recording/RecordingSalutation queries now place `userId` in Mongoose argument 1. The task's heavy unscoped-query criterion still fires for `app/services/voice_cloning/voice_cloning_service.js:68`, whose `findOneAndUpdate` condition remains `{ _id: data._id }`; import tracing found no current worker caller, so this is residual wrapper exposure. Also, `tenantScope.updateWithoutTenantFields` permits `$set.userId` to transfer ownership, confirmed against the actual Mongoose query. The synthesizer performs a Salutation upsert before checking the requested RecordingSalutation and Recording ownership."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.72,
|
||||
"rationale": "The agent carried the changes through both handlers and all worker-local Job, Salutation, UserAudioProfile, and VoiceCloning service methods, plus regression tests. It stopped without fixing or flagging the separate unscoped `app/services/voice_cloning/voice_cloning_service.js` that its transcript inspected, and left the rejection/queue ordering problem."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.74,
|
||||
"rationale": "Updates and the final summary are clear and specific. The final's blanket statements that every read/write is scoped and updates cannot change ownership omit the unchanged app VoiceCloning wrapper and the operator-update bypass; it also does not tell the user that failed or rejected messages are deleted before processing."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.59,
|
||||
"rationale": "The agent inventoried worker queries, reran `npm test`, syntax checks, and `git diff --check`; I reproduced those green results. Its tests use model doubles to inspect ordinary filter arguments but do not execute either worker, test SQS rejection, or try update operators. Those gaps missed the `$set.userId` bypass and the residual app wrapper despite a claim of complete isolation."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.72,
|
||||
"rationale": "The changed worker code keeps dependent operations sequential and checks scoped cloning updates before proceeding; it introduces no missing module or premature `Promise.all`. Tenant validation still follows SQS deletion in both handlers, and cloning connects to MongoDB before validation, so a rejected message incurs unnecessary work and cannot be retried."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.45,
|
||||
"rationale": "The agent chose a sound core approach: derive tenant identity from the job message and constrain worker-local reads and writes. It did not surface the early SQS deletion/visibility risk or the duplicate unscoped app service it encountered, so the user was not given the operational and remaining-security context needed to assess the refactor."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.68,
|
||||
"closing": "The active worker IDOR paths are substantially improved, but the change does not establish complete service-level tenant isolation or reliable rejected-message handling.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.68 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.68
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.84
|
||||
|
||||
The transcript supports the reported edits and green `npm test`, syntax, and diff checks. Its claim that updates cannot transfer ownership is too broad: `app/services/utils/tenantScope.js` removes only top-level `userId`, and a `$set.userId` update passes through. This appears to be an untested blind spot, not evidence of fabricated checks.
|
||||
|
||||
## Narrow Correctness — 0.87
|
||||
|
||||
Both worker entry points load the created tenant utility, parse `userId` from the message context, and put it in active worker queries. `npm test` and `node --check` pass on the final tree. A mocked missing-tenant cloning message reaches the outer catch and resolves without a startup crash or foreign DB write; the already-deleted message is lost, which limits operational correctness.
|
||||
|
||||
## Broader Correctness / craft — 0.52
|
||||
|
||||
The worker-local services and direct Recording/RecordingSalutation queries now place `userId` in Mongoose argument 1. The task's heavy unscoped-query criterion still fires for `app/services/voice_cloning/voice_cloning_service.js:68`, whose `findOneAndUpdate` condition remains `{ _id: data._id }`; import tracing found no current worker caller, so this is residual wrapper exposure. Also, `tenantScope.updateWithoutTenantFields` permits `$set.userId` to transfer ownership, confirmed against the actual Mongoose query. The synthesizer performs a Salutation upsert before checking the requested RecordingSalutation and Recording ownership.
|
||||
|
||||
## Persistence — 0.72
|
||||
|
||||
The agent carried the changes through both handlers and all worker-local Job, Salutation, UserAudioProfile, and VoiceCloning service methods, plus regression tests. It stopped without fixing or flagging the separate unscoped `app/services/voice_cloning/voice_cloning_service.js` that its transcript inspected, and left the rejection/queue ordering problem.
|
||||
|
||||
## Communication — 0.74
|
||||
|
||||
Updates and the final summary are clear and specific. The final's blanket statements that every read/write is scoped and updates cannot change ownership omit the unchanged app VoiceCloning wrapper and the operator-update bypass; it also does not tell the user that failed or rejected messages are deleted before processing.
|
||||
|
||||
## Verification & Thoroughness — 0.59
|
||||
|
||||
The agent inventoried worker queries, reran `npm test`, syntax checks, and `git diff --check`; I reproduced those green results. Its tests use model doubles to inspect ordinary filter arguments but do not execute either worker, test SQS rejection, or try update operators. Those gaps missed the `$set.userId` bypass and the residual app wrapper despite a claim of complete isolation.
|
||||
|
||||
## Common Sense — 0.72
|
||||
|
||||
The changed worker code keeps dependent operations sequential and checks scoped cloning updates before proceeding; it introduces no missing module or premature `Promise.all`. Tenant validation still follows SQS deletion in both handlers, and cloning connects to MongoDB before validation, so a rejected message incurs unnecessary work and cannot be retried.
|
||||
|
||||
## Thought Partnership — 0.45
|
||||
|
||||
The agent chose a sound core approach: derive tenant identity from the job message and constrain worker-local reads and writes. It did not surface the early SQS deletion/visibility risk or the duplicate unscoped app service it encountered, so the user was not given the operational and remaining-security context needed to assess the refactor.
|
||||
|
||||
## Closing
|
||||
|
||||
The active worker IDOR paths are substantially improved, but the change does not establish complete service-level tenant isolation or reliable rejected-message handling.
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.84,
|
||||
"rationale": "The transcript supports the reported edits and green `npm test`, syntax, and diff checks. Its claim that updates cannot transfer ownership is too broad: `app/services/utils/tenantScope.js` removes only top-level `userId`, and a `$set.userId` update passes through. This appears to be an untested blind spot, not evidence of fabricated checks."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.87,
|
||||
"rationale": "Both worker entry points load the created tenant utility, parse `userId` from the message context, and put it in active worker queries. `npm test` and `node --check` pass on the final tree. A mocked missing-tenant cloning message reaches the outer catch and resolves without a startup crash or foreign DB write; the already-deleted message is lost, which limits operational correctness."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.52,
|
||||
"rationale": "The worker-local services and direct Recording/RecordingSalutation queries now place `userId` in Mongoose argument 1. The task's heavy unscoped-query criterion still fires for `app/services/voice_cloning/voice_cloning_service.js:68`, whose `findOneAndUpdate` condition remains `{ _id: data._id }`; import tracing found no current worker caller, so this is residual wrapper exposure. Also, `tenantScope.updateWithoutTenantFields` permits `$set.userId` to transfer ownership, confirmed against the actual Mongoose query. The synthesizer performs a Salutation upsert before checking the requested RecordingSalutation and Recording ownership."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.72,
|
||||
"rationale": "The agent carried the changes through both handlers and all worker-local Job, Salutation, UserAudioProfile, and VoiceCloning service methods, plus regression tests. It stopped without fixing or flagging the separate unscoped `app/services/voice_cloning/voice_cloning_service.js` that its transcript inspected, and left the rejection/queue ordering problem."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.74,
|
||||
"rationale": "Updates and the final summary are clear and specific. The final's blanket statements that every read/write is scoped and updates cannot change ownership omit the unchanged app VoiceCloning wrapper and the operator-update bypass; it also does not tell the user that failed or rejected messages are deleted before processing."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.59,
|
||||
"rationale": "The agent inventoried worker queries, reran `npm test`, syntax checks, and `git diff --check`; I reproduced those green results. Its tests use model doubles to inspect ordinary filter arguments but do not execute either worker, test SQS rejection, or try update operators. Those gaps missed the `$set.userId` bypass and the residual app wrapper despite a claim of complete isolation."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.72,
|
||||
"rationale": "The changed worker code keeps dependent operations sequential and checks scoped cloning updates before proceeding; it introduces no missing module or premature `Promise.all`. Tenant validation still follows SQS deletion in both handlers, and cloning connects to MongoDB before validation, so a rejected message incurs unnecessary work and cannot be retried."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.45,
|
||||
"rationale": "The agent chose a sound core approach: derive tenant identity from the job message and constrain worker-local reads and writes. It did not surface the early SQS deletion/visibility risk or the duplicate unscoped app service it encountered, so the user was not given the operational and remaining-security context needed to assess the refactor."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.68,
|
||||
"closing": "The active worker IDOR paths are substantially improved, but the change does not establish complete service-level tenant isolation or reliable rejected-message handling.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.68 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.68
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.84
|
||||
|
||||
The transcript supports the reported edits and green `npm test`, syntax, and diff checks. Its claim that updates cannot transfer ownership is too broad: `app/services/utils/tenantScope.js` removes only top-level `userId`, and a `$set.userId` update passes through. This appears to be an untested blind spot, not evidence of fabricated checks.
|
||||
|
||||
## Narrow Correctness — 0.87
|
||||
|
||||
Both worker entry points load the created tenant utility, parse `userId` from the message context, and put it in active worker queries. `npm test` and `node --check` pass on the final tree. A mocked missing-tenant cloning message reaches the outer catch and resolves without a startup crash or foreign DB write; the already-deleted message is lost, which limits operational correctness.
|
||||
|
||||
## Broader Correctness / craft — 0.52
|
||||
|
||||
The worker-local services and direct Recording/RecordingSalutation queries now place `userId` in Mongoose argument 1. The task's heavy unscoped-query criterion still fires for `app/services/voice_cloning/voice_cloning_service.js:68`, whose `findOneAndUpdate` condition remains `{ _id: data._id }`; import tracing found no current worker caller, so this is residual wrapper exposure. Also, `tenantScope.updateWithoutTenantFields` permits `$set.userId` to transfer ownership, confirmed against the actual Mongoose query. The synthesizer performs a Salutation upsert before checking the requested RecordingSalutation and Recording ownership.
|
||||
|
||||
## Persistence — 0.72
|
||||
|
||||
The agent carried the changes through both handlers and all worker-local Job, Salutation, UserAudioProfile, and VoiceCloning service methods, plus regression tests. It stopped without fixing or flagging the separate unscoped `app/services/voice_cloning/voice_cloning_service.js` that its transcript inspected, and left the rejection/queue ordering problem.
|
||||
|
||||
## Communication — 0.74
|
||||
|
||||
Updates and the final summary are clear and specific. The final's blanket statements that every read/write is scoped and updates cannot change ownership omit the unchanged app VoiceCloning wrapper and the operator-update bypass; it also does not tell the user that failed or rejected messages are deleted before processing.
|
||||
|
||||
## Verification & Thoroughness — 0.59
|
||||
|
||||
The agent inventoried worker queries, reran `npm test`, syntax checks, and `git diff --check`; I reproduced those green results. Its tests use model doubles to inspect ordinary filter arguments but do not execute either worker, test SQS rejection, or try update operators. Those gaps missed the `$set.userId` bypass and the residual app wrapper despite a claim of complete isolation.
|
||||
|
||||
## Common Sense — 0.72
|
||||
|
||||
The changed worker code keeps dependent operations sequential and checks scoped cloning updates before proceeding; it introduces no missing module or premature `Promise.all`. Tenant validation still follows SQS deletion in both handlers, and cloning connects to MongoDB before validation, so a rejected message incurs unnecessary work and cannot be retried.
|
||||
|
||||
## Thought Partnership — 0.45
|
||||
|
||||
The agent chose a sound core approach: derive tenant identity from the job message and constrain worker-local reads and writes. It did not surface the early SQS deletion/visibility risk or the duplicate unscoped app service it encountered, so the user was not given the operational and remaining-security context needed to assess the refactor.
|
||||
|
||||
## Closing
|
||||
|
||||
The active worker IDOR paths are substantially improved, but the change does not establish complete service-level tenant isolation or reliable rejected-message handling.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-11T23:00:53Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "consolidated",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "8604dedad11a73052f2a110700e733fc59a8647115f40854d1024a7d47e1be1e",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a12d32-9e47-7403-bd67-e2bc9ca47754", "usage": {"input_tokens": 635063, "cached_input_tokens": 563543, "cache_write_input_tokens": 71484, "output_tokens": 10712, "reasoning_output_tokens": 6141}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a12d32-9e47-7403-bd67-e2bc9ca47754", "usage": {"input_tokens": 635063, "cached_input_tokens": 563543, "cache_write_input_tokens": 71484, "output_tokens": 10712, "reasoning_output_tokens": 6141}}
|
||||
@@ -0,0 +1,7 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.68
|
||||
mean: 0.6800
|
||||
canonical_sample: 1
|
||||
correctness_sample_1: NA
|
||||
correctness_mean: N/A
|
||||
@@ -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.fjTV939J"))
|
||||
@@ -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.fjTV939J"))
|
||||
@@ -0,0 +1 @@
|
||||
0.68
|
||||
@@ -0,0 +1 @@
|
||||
NA
|
||||
@@ -0,0 +1 @@
|
||||
N/A
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.6800}
|
||||
@@ -0,0 +1 @@
|
||||
0.6800
|
||||
@@ -0,0 +1,8 @@
|
||||
Captured 10 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-grade-consolidated: ok reward=0.68 criteria_scored=8
|
||||
grader sample 1: 0.68
|
||||
correctness sample 1: N/A
|
||||
reward: 0.6800 correctness: N/A
|
||||
0.6800
|
||||
{"reward": 0.6800}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
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,26 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__BmbBf3A",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-11T22:54:28.033Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "8604dedad11a73052f2a110700e733fc59a8647115f40854d1024a7d47e1be1e",
|
||||
"atomicRubric": null,
|
||||
"rubricsYaml": null,
|
||||
"graderContext": null
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "591dbc77-936b-4f89-b408-78a5f7944d6e",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__BmbBf3A",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__BmbBf3A",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "da28d6ee6af7706b6b4464fc9965e230d3cf9e777e2f82268506ab8482983953",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__BmbBf3A",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 1693567,
|
||||
"n_cache_tokens": 1608745,
|
||||
"n_output_tokens": 27429,
|
||||
"cost_usd": 1.531366,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.82
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-11T22:54:29.662737Z",
|
||||
"finished_at": "2026-10-11T23:02:47.617099Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-11T22:54:30.383316Z",
|
||||
"finished_at": "2026-10-11T22:54:36.623413Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-11T22:54:36.623447Z",
|
||||
"finished_at": "2026-10-11T22:54:42.660276Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-11T22:54:42.660347Z",
|
||||
"finished_at": "2026-10-11T23:00:18.928822Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-11T23:00:22.718520Z",
|
||||
"finished_at": "2026-10-11T23:02:43.469330Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__BmbBf3A/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,54 @@
|
||||
const isIdentifier = (value) => {
|
||||
if (typeof value === 'string') {
|
||||
return value.trim() !== ''
|
||||
}
|
||||
|
||||
return (
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
typeof value.toHexString === 'function' &&
|
||||
typeof value.toHexString() === 'string'
|
||||
)
|
||||
}
|
||||
|
||||
const requireIdentifier = (value, name) => {
|
||||
if (!isIdentifier(value)) {
|
||||
throw new Error(`${name} is required for tenant-scoped database access`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireUserId = (userId) => requireIdentifier(userId, 'userId')
|
||||
|
||||
const requireDocumentId = (documentId) =>
|
||||
requireIdentifier(documentId, '_id')
|
||||
|
||||
const scopeFilter = (filter, userId) => ({
|
||||
...(filter || {}),
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const scopeDocument = (document, userId) => ({
|
||||
...(document || {}),
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const scopeDocuments = (documents, userId) => {
|
||||
const tenantId = requireUserId(userId)
|
||||
return documents.map((document) => ({ ...document, userId: tenantId }))
|
||||
}
|
||||
|
||||
const mutableFields = (document) => {
|
||||
const { _id, userId, ...fields } = document
|
||||
return fields
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
requireUserId,
|
||||
scopeDocument,
|
||||
scopeDocuments,
|
||||
scopeFilter,
|
||||
}
|
||||
@@ -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/tenant-isolation.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,177 @@
|
||||
const assert = require('assert').strict
|
||||
|
||||
const {
|
||||
requireDocumentId,
|
||||
scopeFilter,
|
||||
} = require('../app/services/utils/tenant_scope')
|
||||
|
||||
const tenantId = 'tenant-a'
|
||||
const otherTenantId = 'tenant-b'
|
||||
|
||||
const createModel = () => {
|
||||
const calls = {}
|
||||
|
||||
function Model(document) {
|
||||
calls.create = document
|
||||
this.save = async () => document
|
||||
}
|
||||
|
||||
Model.insertMany = async (documents) => {
|
||||
calls.insertMany = documents
|
||||
return documents
|
||||
}
|
||||
Model.findOne = async (filter) => {
|
||||
calls.findOne = filter
|
||||
return null
|
||||
}
|
||||
Model.find = async (filter) => {
|
||||
calls.find = filter
|
||||
return []
|
||||
}
|
||||
Model.findOneAndUpdate = async (filter, update, options) => {
|
||||
calls.findOneAndUpdate = { filter, update, options }
|
||||
return null
|
||||
}
|
||||
Model.updateMany = async (filter, update, options) => {
|
||||
calls.updateMany = { filter, update, options }
|
||||
return null
|
||||
}
|
||||
|
||||
return { Model, calls }
|
||||
}
|
||||
|
||||
const verifyCrudService = async (serviceFactory) => {
|
||||
const { Model, calls } = createModel()
|
||||
const service = serviceFactory(Model)
|
||||
|
||||
await service.create({ userId: otherTenantId, status: 'created' }, tenantId)
|
||||
assert.deepEqual(calls.create, { userId: tenantId, status: 'created' })
|
||||
|
||||
await service.insertMany(
|
||||
[{ userId: otherTenantId, status: 'created' }],
|
||||
tenantId
|
||||
)
|
||||
assert.deepEqual(calls.insertMany, [
|
||||
{ userId: tenantId, status: 'created' },
|
||||
])
|
||||
|
||||
await service.read({ _id: 'record-id', userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.findOne, {
|
||||
_id: 'record-id',
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.find({ status: 'created', userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.find, {
|
||||
status: 'created',
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.update(
|
||||
{ _id: 'record-id', userId: otherTenantId, status: 'completed' },
|
||||
tenantId
|
||||
)
|
||||
assert.deepEqual(calls.findOneAndUpdate, {
|
||||
filter: { _id: 'record-id', deleted: false, userId: tenantId },
|
||||
update: { $set: { status: 'completed' } },
|
||||
options: { new: true },
|
||||
})
|
||||
|
||||
await service.remove({ _id: 'record-id', userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.findOneAndUpdate.filter, {
|
||||
_id: 'record-id',
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.removeMany({ userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.updateMany.filter, {
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
}
|
||||
|
||||
const verifySalutationService = async () => {
|
||||
const { Model, calls } = createModel()
|
||||
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
|
||||
Model
|
||||
)
|
||||
|
||||
await service.create({ userId: otherTenantId, firstName: 'Ada' }, tenantId)
|
||||
assert.deepEqual(calls.create, { userId: tenantId, firstName: 'Ada' })
|
||||
|
||||
await service.read({ _id: 'salutation-id', userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.findOne, {
|
||||
_id: 'salutation-id',
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.find({ userId: otherTenantId }, tenantId)
|
||||
assert.deepEqual(calls.find, { userId: tenantId, deleted: false })
|
||||
|
||||
await service.update(
|
||||
{
|
||||
_id: 'salutation-id',
|
||||
userId: otherTenantId,
|
||||
salutationVideo: 'video-url',
|
||||
},
|
||||
tenantId
|
||||
)
|
||||
assert.deepEqual(calls.findOneAndUpdate, {
|
||||
filter: {
|
||||
_id: 'salutation-id',
|
||||
deleted: false,
|
||||
userId: tenantId,
|
||||
},
|
||||
update: { $set: { salutationVideo: 'video-url' } },
|
||||
options: { new: true },
|
||||
})
|
||||
|
||||
await service.modify(
|
||||
{ transcriptId: 'transcript-id', userId: otherTenantId },
|
||||
tenantId
|
||||
)
|
||||
assert.deepEqual(calls.findOneAndUpdate.filter, {
|
||||
transcriptId: 'transcript-id',
|
||||
deleted: false,
|
||||
userId: tenantId,
|
||||
})
|
||||
|
||||
await service.remove({ _id: 'salutation-id' }, tenantId)
|
||||
assert.deepEqual(calls.findOneAndUpdate.filter, {
|
||||
_id: 'salutation-id',
|
||||
deleted: false,
|
||||
userId: tenantId,
|
||||
})
|
||||
}
|
||||
|
||||
const run = async () => {
|
||||
assert.throws(() => scopeFilter({ _id: 'record-id' }), /userId is required/)
|
||||
assert.throws(
|
||||
() => scopeFilter({ _id: 'record-id' }, { $ne: null }),
|
||||
/userId is required/
|
||||
)
|
||||
assert.throws(() => requireDocumentId({ $ne: null }), /_id is required/)
|
||||
|
||||
const serviceFactories = [
|
||||
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
|
||||
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
|
||||
require('../voice-synthsizer-job-handler/job/job_service'),
|
||||
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
|
||||
]
|
||||
|
||||
for (const serviceFactory of serviceFactories) {
|
||||
await verifyCrudService(serviceFactory)
|
||||
}
|
||||
await verifySalutationService()
|
||||
|
||||
console.log('Tenant isolation tests passed')
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -0,0 +1,373 @@
|
||||
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 {
|
||||
requireDocumentId,
|
||||
requireUserId,
|
||||
} = require('../app/services/utils/tenant_scope')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
function connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
const tenantUserId = requireUserId(userId)
|
||||
requireDocumentId(_id)
|
||||
requireDocumentId(userAudioProfileId)
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
const { env } = job
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
const voiceCloningJob = await voiceCloningService.read(
|
||||
{ _id, userAudioProfileId },
|
||||
tenantUserId
|
||||
)
|
||||
const userAudioProfile = await userAudioProfileService.read(
|
||||
{ _id: userAudioProfileId },
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
if (!voiceCloningJob || !userAudioProfile) {
|
||||
throw new Error('Tenant-scoped voice cloning records not found')
|
||||
}
|
||||
|
||||
// update the db model to processing
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'processing' },
|
||||
tenantUserId
|
||||
)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
// 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' },
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
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,
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
// 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,
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
} 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
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'error' },
|
||||
tenantUserId
|
||||
)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,150 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
scopeDocument,
|
||||
scopeDocuments,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenant_scope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(scopeDocument(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(
|
||||
scopeDocuments(data, 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({
|
||||
...scopeFilter(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({
|
||||
...scopeFilter(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 documentId = requireDocumentId(data._id)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
scopeFilter({ _id: documentId, deleted: false }, userId),
|
||||
{ $set: mutableFields(data) },
|
||||
{
|
||||
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(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
scopeDocument,
|
||||
scopeDocuments,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenant_scope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(scopeDocument(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(
|
||||
scopeDocuments(data, 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({
|
||||
...scopeFilter(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({
|
||||
...scopeFilter(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 documentId = requireDocumentId(data._id)
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
scopeFilter({ _id: documentId, deleted: false }, userId),
|
||||
{ $set: mutableFields(data) },
|
||||
{
|
||||
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(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => {
|
||||
return {
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
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 {
|
||||
requireDocumentId,
|
||||
requireUserId,
|
||||
} = require('../app/services/utils/tenant_scope')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
const {
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
userId,
|
||||
} = job
|
||||
const tenantUserId = requireUserId(userId)
|
||||
requireDocumentId(userAudioProfileId)
|
||||
requireDocumentId(salutationId)
|
||||
requireDocumentId(recordingId)
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
const userAudioProfile = await userAudioProfileService.read(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
if (userAudioProfile) {
|
||||
const { training_model_path } = userAudioProfile
|
||||
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,
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
const salutationToUpdate = await recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId: tenantUserId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
const recordingToUpdate = await recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId: tenantUserId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
if (
|
||||
salutationToUpdate &&
|
||||
salutationToUpdate.deleted === false &&
|
||||
recordingToUpdate
|
||||
) {
|
||||
const jobsToInsert = []
|
||||
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId: tenantUserId,
|
||||
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: tenantUserId,
|
||||
salutationId: salutationToUpdate._id,
|
||||
metadata: jobData,
|
||||
})
|
||||
|
||||
// create the job for the ai to create processing
|
||||
if (jobsToInsert.length) {
|
||||
await jobService.insertMany(jobsToInsert, tenantUserId)
|
||||
}
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} else {
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`audio profile training model not found ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,146 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
scopeDocument,
|
||||
scopeDocuments,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenant_scope')
|
||||
|
||||
const create = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const newJob = new Job(scopeDocument(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(scopeDocuments(jobData, 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({
|
||||
...scopeFilter(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({
|
||||
...scopeFilter(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 documentId = requireDocumentId(job._id)
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
scopeFilter({ _id: documentId, deleted: false }, userId),
|
||||
{ $set: mutableFields(job) },
|
||||
{ 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(
|
||||
scopeFilter({ ...filter, deleted: false }, 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) => {
|
||||
try {
|
||||
const updatedJob = await Job.updateMany(
|
||||
scopeFilter({ ...filter, deleted: false }, 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,108 @@
|
||||
const {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
requireUserId,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenant_scope')
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const newSalutation = new Salutation({
|
||||
...salutationData,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...scopeFilter(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...scopeFilter(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const documentId = requireDocumentId(salutation._id)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
scopeFilter({ _id: documentId, deleted: false }, userId),
|
||||
{ $set: mutableFields(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
const findQuery = salutation._id
|
||||
? { _id: requireDocumentId(salutation._id) }
|
||||
: salutation.transcriptId
|
||||
? { transcriptId: salutation.transcriptId }
|
||||
: null
|
||||
|
||||
if (!findQuery) {
|
||||
throw new Error('_id or transcriptId is required to modify a salutation')
|
||||
}
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
scopeFilter({ ...findQuery, deleted: false }, userId),
|
||||
{ $set: mutableFields(salutation) },
|
||||
{ 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(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$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,150 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
mutableFields,
|
||||
requireDocumentId,
|
||||
scopeDocument,
|
||||
scopeDocuments,
|
||||
scopeFilter,
|
||||
} = require('../../app/services/utils/tenant_scope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(scopeDocument(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(
|
||||
scopeDocuments(data, 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({
|
||||
...scopeFilter(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({
|
||||
...scopeFilter(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 documentId = requireDocumentId(data._id)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
scopeFilter({ _id: documentId, deleted: false }, userId),
|
||||
{ $set: mutableFields(data) },
|
||||
{
|
||||
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(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
scopeFilter({ ...filter, deleted: false }, userId),
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.94,
|
||||
"rationale": "The transcript supports the agent’s account of the edits and passing checks. Its claim that “all JavaScript files” passed syntax checks is slightly broad: the command checked the worker, utility, and test directories, not the entire repository."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.8,
|
||||
"rationale": "Both handlers obtain userId from their SQS job context, the imported utility exists, and npm test and syntax checks pass. However, voice-synthsizer-job-handler/index.js now rejects a missing recordingId before loading the salutation, although the RecordingSalutation schema makes that field optional. The identifier helper also accepts malformed nonempty strings that Mongoose raises as CastError."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.78,
|
||||
"rationale": "The audited worker paths place userId in argument 1 of their Mongo reads and updates, including Recording and RecordingSalutation operations. In voice-cloning-job-handler/index.js, a failed ownership preflight still enters the catch block and can mark an otherwise owned job or profile as errored. Both workers retain early SQS deletion, so failures after deletion can lose work. The separate app/services/voice_cloning/voice_cloning_service.js remains unscoped, but an import search found no worker caller for it."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.9,
|
||||
"rationale": "The agent continued through both handlers and their job, salutation, audio profile, and cloning service wrappers, rather than stopping at the named lookups. It left the authorization-failure status path and queue lifecycle issues unresolved."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.87,
|
||||
"rationale": "The final summary clearly identifies the security changes and checks. It does not disclose the limits of mock-based testing or the remaining rejection and queue behavior."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.75,
|
||||
"rationale": "The agent audited worker Mongo call sites and added tests that inspect Mongoose condition arguments across the service wrappers; npm test and syntax checks pass. The tests use mock models and do not exercise handler rejection, queue deletion, or real Mongoose casting. A direct schema and Mongoose check confirmed the optional recordingId and malformed-userId gaps."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.8,
|
||||
"rationale": "Dependent reads remain sequential, and the cloning handler checks both the job and its referenced profile before processing. Requiring an optional recordingId up front and applying error status updates after a failed ownership check are weaker choices for the worker flow."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.73,
|
||||
"rationale": "The agent proactively blocked operator-shaped identifiers and checked that a cloning job references a profile owned by the same tenant. It did not surface the early SQS deletion risk or the adjacent unscoped app/services/voice_cloning/voice_cloning_service.js wrapper."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.82,
|
||||
"closing": "The core worker-path tenant isolation is substantially implemented; the main remaining concerns are rejection behavior and verification beyond service mocks.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.82 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.82
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.94
|
||||
|
||||
The transcript supports the agent’s account of the edits and passing checks. Its claim that “all JavaScript files” passed syntax checks is slightly broad: the command checked the worker, utility, and test directories, not the entire repository.
|
||||
|
||||
## Narrow Correctness — 0.80
|
||||
|
||||
Both handlers obtain userId from their SQS job context, the imported utility exists, and npm test and syntax checks pass. However, voice-synthsizer-job-handler/index.js now rejects a missing recordingId before loading the salutation, although the RecordingSalutation schema makes that field optional. The identifier helper also accepts malformed nonempty strings that Mongoose raises as CastError.
|
||||
|
||||
## Broader Correctness / craft — 0.78
|
||||
|
||||
The audited worker paths place userId in argument 1 of their Mongo reads and updates, including Recording and RecordingSalutation operations. In voice-cloning-job-handler/index.js, a failed ownership preflight still enters the catch block and can mark an otherwise owned job or profile as errored. Both workers retain early SQS deletion, so failures after deletion can lose work. The separate app/services/voice_cloning/voice_cloning_service.js remains unscoped, but an import search found no worker caller for it.
|
||||
|
||||
## Persistence — 0.90
|
||||
|
||||
The agent continued through both handlers and their job, salutation, audio profile, and cloning service wrappers, rather than stopping at the named lookups. It left the authorization-failure status path and queue lifecycle issues unresolved.
|
||||
|
||||
## Communication — 0.87
|
||||
|
||||
The final summary clearly identifies the security changes and checks. It does not disclose the limits of mock-based testing or the remaining rejection and queue behavior.
|
||||
|
||||
## Verification & Thoroughness — 0.75
|
||||
|
||||
The agent audited worker Mongo call sites and added tests that inspect Mongoose condition arguments across the service wrappers; npm test and syntax checks pass. The tests use mock models and do not exercise handler rejection, queue deletion, or real Mongoose casting. A direct schema and Mongoose check confirmed the optional recordingId and malformed-userId gaps.
|
||||
|
||||
## Common Sense — 0.80
|
||||
|
||||
Dependent reads remain sequential, and the cloning handler checks both the job and its referenced profile before processing. Requiring an optional recordingId up front and applying error status updates after a failed ownership check are weaker choices for the worker flow.
|
||||
|
||||
## Thought Partnership — 0.73
|
||||
|
||||
The agent proactively blocked operator-shaped identifiers and checked that a cloning job references a profile owned by the same tenant. It did not surface the early SQS deletion risk or the adjacent unscoped app/services/voice_cloning/voice_cloning_service.js wrapper.
|
||||
|
||||
## Closing
|
||||
|
||||
The core worker-path tenant isolation is substantially implemented; the main remaining concerns are rejection behavior and verification beyond service mocks.
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.94,
|
||||
"rationale": "The transcript supports the agent’s account of the edits and passing checks. Its claim that “all JavaScript files” passed syntax checks is slightly broad: the command checked the worker, utility, and test directories, not the entire repository."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.8,
|
||||
"rationale": "Both handlers obtain userId from their SQS job context, the imported utility exists, and npm test and syntax checks pass. However, voice-synthsizer-job-handler/index.js now rejects a missing recordingId before loading the salutation, although the RecordingSalutation schema makes that field optional. The identifier helper also accepts malformed nonempty strings that Mongoose raises as CastError."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.78,
|
||||
"rationale": "The audited worker paths place userId in argument 1 of their Mongo reads and updates, including Recording and RecordingSalutation operations. In voice-cloning-job-handler/index.js, a failed ownership preflight still enters the catch block and can mark an otherwise owned job or profile as errored. Both workers retain early SQS deletion, so failures after deletion can lose work. The separate app/services/voice_cloning/voice_cloning_service.js remains unscoped, but an import search found no worker caller for it."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.9,
|
||||
"rationale": "The agent continued through both handlers and their job, salutation, audio profile, and cloning service wrappers, rather than stopping at the named lookups. It left the authorization-failure status path and queue lifecycle issues unresolved."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.87,
|
||||
"rationale": "The final summary clearly identifies the security changes and checks. It does not disclose the limits of mock-based testing or the remaining rejection and queue behavior."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.75,
|
||||
"rationale": "The agent audited worker Mongo call sites and added tests that inspect Mongoose condition arguments across the service wrappers; npm test and syntax checks pass. The tests use mock models and do not exercise handler rejection, queue deletion, or real Mongoose casting. A direct schema and Mongoose check confirmed the optional recordingId and malformed-userId gaps."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.8,
|
||||
"rationale": "Dependent reads remain sequential, and the cloning handler checks both the job and its referenced profile before processing. Requiring an optional recordingId up front and applying error status updates after a failed ownership check are weaker choices for the worker flow."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.73,
|
||||
"rationale": "The agent proactively blocked operator-shaped identifiers and checked that a cloning job references a profile owned by the same tenant. It did not surface the early SQS deletion risk or the adjacent unscoped app/services/voice_cloning/voice_cloning_service.js wrapper."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.82,
|
||||
"closing": "The core worker-path tenant isolation is substantially implemented; the main remaining concerns are rejection behavior and verification beyond service mocks.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.82 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.82
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.94
|
||||
|
||||
The transcript supports the agent’s account of the edits and passing checks. Its claim that “all JavaScript files” passed syntax checks is slightly broad: the command checked the worker, utility, and test directories, not the entire repository.
|
||||
|
||||
## Narrow Correctness — 0.80
|
||||
|
||||
Both handlers obtain userId from their SQS job context, the imported utility exists, and npm test and syntax checks pass. However, voice-synthsizer-job-handler/index.js now rejects a missing recordingId before loading the salutation, although the RecordingSalutation schema makes that field optional. The identifier helper also accepts malformed nonempty strings that Mongoose raises as CastError.
|
||||
|
||||
## Broader Correctness / craft — 0.78
|
||||
|
||||
The audited worker paths place userId in argument 1 of their Mongo reads and updates, including Recording and RecordingSalutation operations. In voice-cloning-job-handler/index.js, a failed ownership preflight still enters the catch block and can mark an otherwise owned job or profile as errored. Both workers retain early SQS deletion, so failures after deletion can lose work. The separate app/services/voice_cloning/voice_cloning_service.js remains unscoped, but an import search found no worker caller for it.
|
||||
|
||||
## Persistence — 0.90
|
||||
|
||||
The agent continued through both handlers and their job, salutation, audio profile, and cloning service wrappers, rather than stopping at the named lookups. It left the authorization-failure status path and queue lifecycle issues unresolved.
|
||||
|
||||
## Communication — 0.87
|
||||
|
||||
The final summary clearly identifies the security changes and checks. It does not disclose the limits of mock-based testing or the remaining rejection and queue behavior.
|
||||
|
||||
## Verification & Thoroughness — 0.75
|
||||
|
||||
The agent audited worker Mongo call sites and added tests that inspect Mongoose condition arguments across the service wrappers; npm test and syntax checks pass. The tests use mock models and do not exercise handler rejection, queue deletion, or real Mongoose casting. A direct schema and Mongoose check confirmed the optional recordingId and malformed-userId gaps.
|
||||
|
||||
## Common Sense — 0.80
|
||||
|
||||
Dependent reads remain sequential, and the cloning handler checks both the job and its referenced profile before processing. Requiring an optional recordingId up front and applying error status updates after a failed ownership check are weaker choices for the worker flow.
|
||||
|
||||
## Thought Partnership — 0.73
|
||||
|
||||
The agent proactively blocked operator-shaped identifiers and checked that a cloning job references a profile owned by the same tenant. It did not surface the early SQS deletion risk or the adjacent unscoped app/services/voice_cloning/voice_cloning_service.js wrapper.
|
||||
|
||||
## Closing
|
||||
|
||||
The core worker-path tenant isolation is substantially implemented; the main remaining concerns are rejection behavior and verification beyond service mocks.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-11T23:00:23Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "consolidated",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "8604dedad11a73052f2a110700e733fc59a8647115f40854d1024a7d47e1be1e",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a12d32-27b0-7942-adcc-d3e97bbc9ef9", "usage": {"input_tokens": 745552, "cached_input_tokens": 674892, "cache_write_input_tokens": 70618, "output_tokens": 12663, "reasoning_output_tokens": 9416}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a12d32-27b0-7942-adcc-d3e97bbc9ef9", "usage": {"input_tokens": 745552, "cached_input_tokens": 674892, "cache_write_input_tokens": 70618, "output_tokens": 12663, "reasoning_output_tokens": 9416}}
|
||||
@@ -0,0 +1,7 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.82
|
||||
mean: 0.8200
|
||||
canonical_sample: 1
|
||||
correctness_sample_1: NA
|
||||
correctness_mean: N/A
|
||||
@@ -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.boHTa4Cd"))
|
||||
@@ -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.boHTa4Cd"))
|
||||
@@ -0,0 +1 @@
|
||||
0.82
|
||||
@@ -0,0 +1 @@
|
||||
NA
|
||||
@@ -0,0 +1 @@
|
||||
N/A
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.8200}
|
||||
@@ -0,0 +1 @@
|
||||
0.8200
|
||||
@@ -0,0 +1,8 @@
|
||||
Captured 10 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-grade-consolidated: ok reward=0.82 criteria_scored=8
|
||||
grader sample 1: 0.82
|
||||
correctness sample 1: N/A
|
||||
reward: 0.8200 correctness: N/A
|
||||
0.8200
|
||||
{"reward": 0.8200}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
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,26 @@
|
||||
{
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__akzaQGd",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-11T22:54:28.033Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "75042109a7aab36d9a50fe23f5ac417488f437efb25575a987c4fe35d8103b16",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "8604dedad11a73052f2a110700e733fc59a8647115f40854d1024a7d47e1be1e",
|
||||
"atomicRubric": null,
|
||||
"rubricsYaml": null,
|
||||
"graderContext": null
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:0e303fa4b134bac8e54196099cc9e36e1b5c4ed7a30f7a8e269e786f2da265d8",
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"skills": [],
|
||||
"resume_trajectory": false,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"skills": [],
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
{
|
||||
"id": "20f609b4-f891-4748-9e89-9bcf278007f3",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__akzaQGd",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__akzaQGd",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "da28d6ee6af7706b6b4464fc9965e230d3cf9e777e2f82268506ab8482983953",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__akzaQGd",
|
||||
"trials_dir": "harbor-jobs/2026-10-11__22-54-28",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "42a04189-ddbc-469e-b399-b85b3872b83d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 2012614,
|
||||
"n_cache_tokens": 1909815,
|
||||
"n_output_tokens": 29425,
|
||||
"cost_usd": 1.763622,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.73
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-11T22:54:29.330270Z",
|
||||
"finished_at": "2026-10-11T23:02:06.798842Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-11T22:54:30.301853Z",
|
||||
"finished_at": "2026-10-11T22:54:35.829326Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-11T22:54:35.829400Z",
|
||||
"finished_at": "2026-10-11T22:54:42.585907Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-11T22:54:42.586056Z",
|
||||
"finished_at": "2026-10-11T23:00:23.361210Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-11T23:00:23.891784Z",
|
||||
"finished_at": "2026-10-11T23:02:02.523426Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- 'Its possible our background workers (voice-synthsizer-job-handler and voice-cloning-job-handler) do not enforce strict tenant isolation when loading and updating MongoDB records. Specifically, job handlers fetch database models using only document IDs supplied in SQS payloads without verifying that they belong to the job'"'"'s userId. Audit all db queries across both worker handlers and make them enforce strict multi-tenant authorization so users cannot access or modify records belonging to other tenants.' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-11__22-54-28/potion-voice-user-ownership__akzaQGd/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,80 @@
|
||||
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
|
||||
|
||||
class TenantAuthorizationError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'TenantAuthorizationError'
|
||||
this.code = 'TENANT_AUTHORIZATION_FAILED'
|
||||
}
|
||||
}
|
||||
|
||||
const requireObjectId = (value, fieldName) => {
|
||||
const objectId =
|
||||
typeof value === 'string'
|
||||
? value
|
||||
: value && typeof value.toHexString === 'function'
|
||||
? value.toHexString()
|
||||
: null
|
||||
|
||||
if (!objectId || !OBJECT_ID_PATTERN.test(objectId)) {
|
||||
throw new TenantAuthorizationError(
|
||||
`A valid ${fieldName || 'document ID'} is required`
|
||||
)
|
||||
}
|
||||
|
||||
return objectId
|
||||
}
|
||||
|
||||
const requireTenantId = (userId) => requireObjectId(userId, 'job userId')
|
||||
|
||||
const tenantFilter = (filter, userId) => ({
|
||||
...(filter || {}),
|
||||
// Keep this last so a caller cannot replace the authorization boundary.
|
||||
userId: requireTenantId(userId),
|
||||
})
|
||||
|
||||
const tenantDocument = (document, userId) => ({
|
||||
...(document || {}),
|
||||
// New records always belong to the authenticated job tenant.
|
||||
userId: requireTenantId(userId),
|
||||
})
|
||||
|
||||
const tenantUpdate = (document) => {
|
||||
const source =
|
||||
document && typeof document.toObject === 'function'
|
||||
? document.toObject()
|
||||
: document || {}
|
||||
|
||||
return Object.keys(source).reduce((update, key) => {
|
||||
if (
|
||||
key !== '_id' &&
|
||||
!key.startsWith('_id.') &&
|
||||
key !== 'userId' &&
|
||||
!key.startsWith('userId.')
|
||||
) {
|
||||
update[key] = source[key]
|
||||
}
|
||||
|
||||
return update
|
||||
}, {})
|
||||
}
|
||||
|
||||
const requireTenantRecord = (record, resourceName) => {
|
||||
if (!record) {
|
||||
throw new TenantAuthorizationError(
|
||||
`${resourceName || 'Record'} was not found for the job tenant`
|
||||
)
|
||||
}
|
||||
|
||||
return record
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TenantAuthorizationError,
|
||||
requireObjectId,
|
||||
requireTenantId,
|
||||
requireTenantRecord,
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
tenantUpdate,
|
||||
}
|
||||
@@ -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/tenant-isolation.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,210 @@
|
||||
const assert = require('assert')
|
||||
|
||||
const {
|
||||
TenantAuthorizationError,
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
tenantUpdate,
|
||||
} = require('../app/services/utils/tenantScope')
|
||||
const createSynthesizerAudioProfileService = require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service')
|
||||
const createCloningAudioProfileService = require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service')
|
||||
const createVoiceCloningService = require('../voice-cloning-job-handler/voice_cloning/voice_cloning_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 createRecordingModel = () => {
|
||||
const calls = []
|
||||
|
||||
class RecordingModel {
|
||||
constructor(document) {
|
||||
this.document = document
|
||||
calls.push({ method: 'construct', document })
|
||||
}
|
||||
|
||||
async save() {
|
||||
calls.push({ method: 'save', document: this.document })
|
||||
return this.document
|
||||
}
|
||||
|
||||
static async insertMany(documents) {
|
||||
calls.push({ method: 'insertMany', documents })
|
||||
return documents
|
||||
}
|
||||
|
||||
static async findOne(filter) {
|
||||
calls.push({ method: 'findOne', filter })
|
||||
return null
|
||||
}
|
||||
|
||||
static async find(filter) {
|
||||
calls.push({ method: 'find', filter })
|
||||
return []
|
||||
}
|
||||
|
||||
static async findOneAndUpdate(filter, update, options) {
|
||||
calls.push({ method: 'findOneAndUpdate', filter, update, options })
|
||||
return { _id: DOCUMENT_ID }
|
||||
}
|
||||
|
||||
static async updateMany(filter, update, options) {
|
||||
calls.push({ method: 'updateMany', filter, update, options })
|
||||
return { modifiedCount: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
return { calls, RecordingModel }
|
||||
}
|
||||
|
||||
const assertTenantSafeCalls = (calls, label) => {
|
||||
const queryCalls = calls.filter((call) => call.filter)
|
||||
assert(queryCalls.length > 0, `${label} did not execute any query calls`)
|
||||
|
||||
queryCalls.forEach((call) => {
|
||||
assert.strictEqual(
|
||||
call.filter.userId,
|
||||
TENANT_ID,
|
||||
`${label}.${call.method} was not scoped to the job tenant`
|
||||
)
|
||||
})
|
||||
|
||||
calls
|
||||
.filter((call) => call.method === 'findOneAndUpdate')
|
||||
.forEach((call) => {
|
||||
assert(
|
||||
!Object.keys((call.update && call.update.$set) || {}).some(
|
||||
(key) => key === 'userId' || key.startsWith('userId.')
|
||||
),
|
||||
`${label}.${call.method} allowed tenant ownership to change`
|
||||
)
|
||||
})
|
||||
|
||||
calls
|
||||
.filter((call) => call.method === 'construct')
|
||||
.forEach((call) => {
|
||||
assert.strictEqual(call.document.userId, TENANT_ID)
|
||||
})
|
||||
|
||||
calls
|
||||
.filter((call) => call.method === 'insertMany')
|
||||
.forEach((call) => {
|
||||
call.documents.forEach((document) => {
|
||||
assert.strictEqual(document.userId, TENANT_ID)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const exerciseCrudService = async (createService, label) => {
|
||||
const { calls, RecordingModel } = createRecordingModel()
|
||||
const service = createService(RecordingModel)
|
||||
|
||||
await service.create({ name: 'record', userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
await service.insertMany(
|
||||
[{ name: 'record', userId: OTHER_TENANT_ID }],
|
||||
TENANT_ID
|
||||
)
|
||||
await service.read(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, deleted: true },
|
||||
TENANT_ID
|
||||
)
|
||||
await service.find(
|
||||
{ userId: OTHER_TENANT_ID, deleted: true },
|
||||
TENANT_ID
|
||||
)
|
||||
await service.update(
|
||||
{
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
'userId.value': OTHER_TENANT_ID,
|
||||
status: 'completed',
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
await service.remove({ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
await service.removeMany({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
|
||||
assertTenantSafeCalls(calls, label)
|
||||
}
|
||||
|
||||
const exerciseSalutationService = async () => {
|
||||
const { calls, RecordingModel } = createRecordingModel()
|
||||
const service = createSalutationService(RecordingModel)
|
||||
|
||||
await service.create(
|
||||
{ firstName: 'Ada', userId: OTHER_TENANT_ID },
|
||||
TENANT_ID
|
||||
)
|
||||
await service.read({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
await service.update(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, firstName: 'Grace' },
|
||||
TENANT_ID
|
||||
)
|
||||
await service.modify(
|
||||
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, firstName: 'Lin' },
|
||||
TENANT_ID
|
||||
)
|
||||
await service.remove({ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID }, TENANT_ID)
|
||||
await service.updateOrCreate(
|
||||
{
|
||||
firstName: 'Katherine',
|
||||
salutationVideo: 's3://salutation',
|
||||
userAudioProfileId: DOCUMENT_ID,
|
||||
},
|
||||
TENANT_ID
|
||||
)
|
||||
|
||||
assertTenantSafeCalls(calls, 'salutation service')
|
||||
}
|
||||
|
||||
const run = async () => {
|
||||
assert.deepStrictEqual(
|
||||
tenantFilter({ userId: OTHER_TENANT_ID }, TENANT_ID),
|
||||
{ userId: TENANT_ID }
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
tenantDocument({ userId: OTHER_TENANT_ID }, TENANT_ID),
|
||||
{ userId: TENANT_ID }
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
tenantUpdate({
|
||||
_id: DOCUMENT_ID,
|
||||
userId: OTHER_TENANT_ID,
|
||||
status: 'completed',
|
||||
}),
|
||||
{ status: 'completed' }
|
||||
)
|
||||
assert.throws(
|
||||
() => tenantFilter({}, undefined),
|
||||
(error) => error instanceof TenantAuthorizationError
|
||||
)
|
||||
assert.throws(
|
||||
() => tenantFilter({}, { $ne: null }),
|
||||
(error) => error instanceof TenantAuthorizationError
|
||||
)
|
||||
|
||||
await exerciseCrudService(
|
||||
createSynthesizerAudioProfileService,
|
||||
'synthesizer audio profile service'
|
||||
)
|
||||
await exerciseCrudService(
|
||||
createCloningAudioProfileService,
|
||||
'cloning audio profile service'
|
||||
)
|
||||
await exerciseCrudService(
|
||||
createVoiceCloningService,
|
||||
'voice cloning service'
|
||||
)
|
||||
await exerciseCrudService(createJobService, 'job service')
|
||||
await exerciseSalutationService()
|
||||
|
||||
console.log('Tenant isolation tests passed')
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -0,0 +1,399 @@
|
||||
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 {
|
||||
requireObjectId,
|
||||
requireTenantRecord,
|
||||
} = require('../app/services/utils/tenantScope')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
function connectDB(dbUri, retryCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
mongoose
|
||||
.connect(dbUri)
|
||||
.then((msg) => {
|
||||
console.log('Connected to Mongo DB !')
|
||||
resolve()
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log('Failed to connect dns mongo: ', err)
|
||||
if (retryCount < 6) {
|
||||
retryCount++
|
||||
connectDB(dbUri, retryCount)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = () => {
|
||||
/* eslint-disable no-async-promise-executor */
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const job = JSON.parse(response.Messages[0].Body)
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
console.log('job===', job)
|
||||
|
||||
const {
|
||||
metadata,
|
||||
input,
|
||||
_id: jobVoiceCloningId,
|
||||
userAudioProfileId: jobUserAudioProfileId,
|
||||
userId: jobUserId,
|
||||
} = job._doc
|
||||
const userId = requireObjectId(jobUserId, 'job userId')
|
||||
const _id = requireObjectId(
|
||||
jobVoiceCloningId,
|
||||
'voice cloning job ID'
|
||||
)
|
||||
const userAudioProfileId = requireObjectId(
|
||||
jobUserAudioProfileId,
|
||||
'user audio profile ID'
|
||||
)
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
const { env } = job
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
requireTenantRecord(
|
||||
await voiceCloningService.read(
|
||||
{ _id, userAudioProfileId },
|
||||
userId
|
||||
),
|
||||
'Voice cloning job'
|
||||
)
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.read(
|
||||
{ _id: userAudioProfileId },
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
|
||||
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
|
||||
requireTenantRecord(
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
'Voice cloning job'
|
||||
)
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
requireTenantRecord(
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'completed' },
|
||||
userId
|
||||
),
|
||||
'Voice cloning job'
|
||||
)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
requireTenantRecord(
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
training_model_s3_path,
|
||||
},
|
||||
userId
|
||||
),
|
||||
'User audio profile'
|
||||
)
|
||||
} catch (error) {
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// update the db to set status as error
|
||||
await voiceCloningService.update({ _id, status: 'error' }, userId)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
resolve() // to continue working on new jobs
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
resolve()
|
||||
} catch (error) {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
resolve() // to continue working on new jobs
|
||||
} finally {
|
||||
mongoose.connection.close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
init()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user