The four trials finished successfully with no exceptions. The mean reward was 0.672.
| Trial | Reward | |---|---:| | 2WLWKV8 | 0.62 | | 7prhyuz | 0.68 | | btsikGq | 0.73 | | vw3sDhc | 0.66 | Results are in harbor-jobs/2026-10-14__18-06-02/result.json (harbor-jobs/2026-10-14__18-06-02/result.json). Worked for 14m 54s • 6:20 PM"feat: Add password reset feature"
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"job_name": "2026-10-14__18-06-02",
|
||||
"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,156 @@
|
||||
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
|
||||
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
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__2WLWKV8/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__btsikGq/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-14__18-06-02/potion-voice-user-ownership__vw3sDhc/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__7prhyuz/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-14T18:06:03.402948Z",
|
||||
"harbor": {
|
||||
"version": "0.20.0",
|
||||
"is_editable": false
|
||||
},
|
||||
"n_concurrent_trials": 4,
|
||||
"retry": {
|
||||
"max_retries": 0,
|
||||
"exclude_exceptions": [
|
||||
"AgentAuthenticationError",
|
||||
"VerifierOutputParseError",
|
||||
"RewardFileEmptyError",
|
||||
"AgentSafetyRefusalError",
|
||||
"RewardFileNotFoundError",
|
||||
"ApiUsageLimitError",
|
||||
"ModelNotFoundError",
|
||||
"VerifierTimeoutError",
|
||||
"AgentTimeoutError"
|
||||
],
|
||||
"wait_multiplier": 1.0,
|
||||
"min_wait_sec": 1.0,
|
||||
"max_wait_sec": 60.0
|
||||
},
|
||||
"trials": [
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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__2WLWKV8",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-14T18:06:01.683Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d0",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
|
||||
"rubricsYaml": null,
|
||||
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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": "11adf47e-c476-4393-8554-7b3ddf8c5681",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__2WLWKV8",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__2WLWKV8",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__2WLWKV8",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 2365074,
|
||||
"n_cache_tokens": 2241832,
|
||||
"n_output_tokens": 43113,
|
||||
"cost_usd": 2.2519608,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.62
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:06:04.485091Z",
|
||||
"finished_at": "2026-10-14T18:18:22.916652Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:06:04.973231Z",
|
||||
"finished_at": "2026-10-14T18:06:23.275618Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:06:23.275640Z",
|
||||
"finished_at": "2026-10-14T18:06:29.131242Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:06:29.131361Z",
|
||||
"finished_at": "2026-10-14T18:15:33.452931Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:15:39.992347Z",
|
||||
"finished_at": "2026-10-14T18:18:18.561493Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__2WLWKV8/agent/trajectory.json
|
||||
Collecting main service artifacts
|
||||
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
|
||||
@@ -0,0 +1,52 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const parseJobMessage = (body) => {
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Queue message body is not valid JSON')
|
||||
}
|
||||
}
|
||||
|
||||
const requireJobObject = (value, fieldName) => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new RejectedJobError(`${fieldName} is required`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireJobObjectId = (value, fieldName) => {
|
||||
const isObjectId = value instanceof mongoose.Types.ObjectId
|
||||
const isObjectIdString =
|
||||
typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value)
|
||||
|
||||
if (!isObjectId && !isObjectIdString) {
|
||||
throw new RejectedJobError(`${fieldName} must be a valid ObjectId`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const requireJobString = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || value.trim() === '') {
|
||||
throw new RejectedJobError(`${fieldName} is required`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const requireUserId = (userId) => {
|
||||
const isObjectId = userId instanceof mongoose.Types.ObjectId
|
||||
const isObjectIdString =
|
||||
typeof userId === 'string' && /^[a-fA-F0-9]{24}$/.test(userId)
|
||||
|
||||
if (!isObjectId && !isObjectIdString) {
|
||||
throw new TypeError(
|
||||
'A valid userId is required for tenant-scoped database access'
|
||||
)
|
||||
}
|
||||
|
||||
return userId
|
||||
}
|
||||
|
||||
const scopeToUser = (filter, userId) => ({
|
||||
...filter,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const assignToUser = (data, userId) => ({
|
||||
...data,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const withoutTenantIdentity = (data) => {
|
||||
const updates = { ...data }
|
||||
delete updates._id
|
||||
delete updates.userId
|
||||
|
||||
if (Object.keys(updates).some((key) => key.startsWith('$'))) {
|
||||
throw new TypeError('MongoDB update operators are not allowed')
|
||||
}
|
||||
|
||||
return updates
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
assignToUser,
|
||||
requireUserId,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let authorized = false
|
||||
let userId
|
||||
let voiceCloningId
|
||||
let userAudioProfileId
|
||||
let receiptHandle
|
||||
let acknowledged = false
|
||||
|
||||
const acknowledgeMessage = async () => {
|
||||
if (!acknowledged && receiptHandle) {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
acknowledged = true
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (!response.Messages || response.Messages.length === 0) {
|
||||
throttleMessageFetching = true
|
||||
return
|
||||
}
|
||||
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = requireJobObject(parseJobMessage(message.Body), 'job')
|
||||
const jobDocument = requireJobObject(job._doc, 'job._doc')
|
||||
|
||||
userId = requireJobObjectId(jobDocument.userId, 'userId')
|
||||
voiceCloningId = requireJobObjectId(jobDocument._id, '_id')
|
||||
userAudioProfileId = requireJobObjectId(
|
||||
jobDocument.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
)
|
||||
const env = requireJobString(job.env, 'env')
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read(
|
||||
{ _id: voiceCloningId, userAudioProfileId },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job records were not found for the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
authorized = true
|
||||
const metadata = requireJobObject(voiceCloning.metadata, 'metadata')
|
||||
const directoryName = requireJobString(
|
||||
metadata.directoryName,
|
||||
'metadata.directoryName'
|
||||
)
|
||||
const input = voiceCloning.input
|
||||
if (!Array.isArray(input)) {
|
||||
throw new RejectedJobError('input must be an array')
|
||||
}
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
// Keep the existing at-most-once processing behavior once the job and all
|
||||
// tenant-owned records have been validated.
|
||||
await acknowledgeMessage()
|
||||
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
|
||||
const [processingJob, processingProfile] = await Promise.all([
|
||||
voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
])
|
||||
if (!processingJob || !processingProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job records changed before processing'
|
||||
)
|
||||
}
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
await execShellCommand(samplingCommand, logPath)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
await execShellCommand(trainingModelCommand, logPath)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
await execShellCommand(minimizeCloningModelCommand, logPath)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'completed' },
|
||||
userId
|
||||
)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
const keys = Object.keys(training_model_path)
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, training_model_s3_path },
|
||||
userId
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn(`Rejected voice cloning job: ${error.message}`)
|
||||
try {
|
||||
await acknowledgeMessage()
|
||||
} catch (acknowledgementError) {
|
||||
console.error('Unable to acknowledge rejected voice cloning job', {
|
||||
error: acknowledgementError,
|
||||
})
|
||||
Bugsnag.notify(acknowledgementError)
|
||||
}
|
||||
} else {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
|
||||
if (authorized) {
|
||||
const statusUpdates = await Promise.allSettled([
|
||||
voiceCloningService.update(
|
||||
{ _id: voiceCloningId, status: 'error' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{ _id: userAudioProfileId, status: 'error' },
|
||||
userId
|
||||
),
|
||||
])
|
||||
statusUpdates
|
||||
.filter(({ status }) => status === 'rejected')
|
||||
.forEach(({ reason }) => Bugsnag.notify(reason))
|
||||
}
|
||||
} finally {
|
||||
if (mongoose.connection.readyState !== 0) {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
connectDB,
|
||||
processQueue,
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await VoiceCloningModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => {
|
||||
return {
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
const {
|
||||
RejectedJobError,
|
||||
parseJobMessage,
|
||||
requireJobObject,
|
||||
requireJobObjectId,
|
||||
requireJobString,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let receiptHandle
|
||||
let acknowledged = false
|
||||
|
||||
const acknowledgeMessage = async () => {
|
||||
if (!acknowledged && receiptHandle) {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
acknowledged = true
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (!response.Messages || response.Messages.length === 0) {
|
||||
throttleMessageFetching = true
|
||||
return
|
||||
}
|
||||
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
receiptHandle = message.ReceiptHandle
|
||||
const job = requireJobObject(parseJobMessage(message.Body), 'job')
|
||||
|
||||
const userId = requireJobObjectId(job.userId, 'userId')
|
||||
const userAudioProfileId = requireJobObjectId(
|
||||
job.userAudioProfileId,
|
||||
'userAudioProfileId'
|
||||
)
|
||||
const salutationId = requireJobObjectId(job.salutationId, 'salutationId')
|
||||
const recordingId = requireJobObjectId(job.recordingId, 'recordingId')
|
||||
const text = requireJobString(job.text, 'text')
|
||||
const firstName = requireJobString(job.firstName, 'firstName')
|
||||
const env = requireJobString(job.env, 'env')
|
||||
const { baseUrlForPotionAi } = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// Authorize every referenced record before voice synthesis or S3 writes.
|
||||
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
|
||||
await Promise.all([
|
||||
userAudioProfileService.read(
|
||||
{ _id: userAudioProfileId, status: 'completed' },
|
||||
userId
|
||||
),
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!userAudioProfile || !salutationToUpdate || !recordingToUpdate) {
|
||||
throw new RejectedJobError(
|
||||
'Synthesizer job records were not found for the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
const trainingModelPath = requireJobObject(
|
||||
userAudioProfile.training_model_path,
|
||||
'training_model_path'
|
||||
)
|
||||
const voiceModelLightPath = requireJobString(
|
||||
trainingModelPath.voice_model_light_path,
|
||||
'training_model_path.voice_model_light_path'
|
||||
)
|
||||
const voiceModelConfigLightPath = requireJobString(
|
||||
trainingModelPath.voice_model_config_light_path,
|
||||
'training_model_path.voice_model_config_light_path'
|
||||
)
|
||||
const voiceModelSpeakersFilePath = requireJobString(
|
||||
trainingModelPath.voice_model_speakers_file_path,
|
||||
'training_model_path.voice_model_speakers_file_path'
|
||||
)
|
||||
|
||||
// Keep the existing at-most-once processing behavior once the job and all
|
||||
// tenant-owned records have been validated.
|
||||
await acknowledgeMessage()
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voiceModelLightPath} --voice_model_config_path ${voiceModelConfigLightPath} --speaker_embeddings_path ${voiceModelSpeakersFilePath} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create or update the per-user cached salutation.
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
const updatedSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedSalutation) {
|
||||
throw new RejectedJobError(
|
||||
'Recording salutation changed before it could be updated'
|
||||
)
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: updatedSalutation._id,
|
||||
firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: updatedSalutation._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
|
||||
await jobService.insertMany(
|
||||
[
|
||||
{
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutationId: updatedSalutation._id,
|
||||
metadata: jobData,
|
||||
},
|
||||
],
|
||||
userId
|
||||
)
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn(`Rejected voice synthesizer job: ${error.message}`)
|
||||
try {
|
||||
await acknowledgeMessage()
|
||||
} catch (acknowledgementError) {
|
||||
console.error('Unable to acknowledge rejected voice synthesizer job', {
|
||||
error: acknowledgementError,
|
||||
})
|
||||
Bugsnag.notify(acknowledgementError)
|
||||
}
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
if (mongoose.connection.readyState !== 0) {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Unable to close Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) {
|
||||
init()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
connectDB,
|
||||
processQueue,
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const newJob = new Job(assignToUser(jobData, userId))
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const inserted = await Job.insertMany(
|
||||
jobData.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const foundJob = await Job.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const foundJobs = await Job.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (Job) => async (job, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(job)
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: job._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedJob = await Job.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (Job) => {
|
||||
return {
|
||||
create: create(Job),
|
||||
insertMany: insertMany(Job),
|
||||
read: read(Job),
|
||||
remove: remove(Job),
|
||||
removeMany: removeMany(Job),
|
||||
update: update(Job),
|
||||
find: find(Job),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const newSalutation = new Salutation(assignToUser(salutationData, userId))
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const updates = withoutTenantIdentity(salutation)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: salutation._id }, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id }
|
||||
: { transcriptId: salutation.transcriptId }
|
||||
const updates = withoutTenantIdentity(salutation)
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(findQuery, userId),
|
||||
deleted: false,
|
||||
},
|
||||
updates,
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
const salutation = await read(Salutation)(
|
||||
{
|
||||
firstName,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
if (salutation) {
|
||||
return await update(Salutation)(
|
||||
{ _id: salutation._id, salutationVideo },
|
||||
userId
|
||||
)
|
||||
} else {
|
||||
return await create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (Salutation) => async (filter, userId) => {
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
module.exports = (Salutation) => {
|
||||
return {
|
||||
create: create(Salutation),
|
||||
read: read(Salutation),
|
||||
remove: remove(Salutation),
|
||||
update: update(Salutation),
|
||||
updateOrCreate: updateOrCreate(Salutation),
|
||||
find: find(Salutation),
|
||||
modify: modify(Salutation),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
assignToUser,
|
||||
scopeToUser,
|
||||
withoutTenantIdentity,
|
||||
} = require('../../app/services/utils/tenantScope')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(assignToUser(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => assignToUser(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const updates = withoutTenantIdentity(data)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser({ _id: data._id }, userId),
|
||||
deleted: false
|
||||
},
|
||||
updates,
|
||||
{
|
||||
new: true
|
||||
}
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{
|
||||
...scopeToUser(filter, userId),
|
||||
deleted: false
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
deleted: true
|
||||
}
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => {
|
||||
return {
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.9,
|
||||
"rationale": "The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.52,
|
||||
"rationale": "Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.6,
|
||||
"rationale": "Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.71,
|
||||
"rationale": "The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.78,
|
||||
"rationale": "The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.48,
|
||||
"rationale": "Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.53,
|
||||
"rationale": "Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.45,
|
||||
"rationale": "The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.58,
|
||||
"closing": "The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.62 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.58
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.90
|
||||
|
||||
The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed.
|
||||
|
||||
## Narrow Correctness — 0.52
|
||||
|
||||
Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update.
|
||||
|
||||
## Broader Correctness / craft — 0.60
|
||||
|
||||
Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads.
|
||||
|
||||
## Persistence — 0.71
|
||||
|
||||
The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path.
|
||||
|
||||
## Communication — 0.78
|
||||
|
||||
The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped.
|
||||
|
||||
## Verification & Thoroughness — 0.48
|
||||
|
||||
Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available.
|
||||
|
||||
## Common Sense — 0.53
|
||||
|
||||
Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged.
|
||||
|
||||
## Thought Partnership — 0.45
|
||||
|
||||
The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task.
|
||||
|
||||
## Closing
|
||||
|
||||
The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.9,
|
||||
"rationale": "The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.52,
|
||||
"rationale": "Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.6,
|
||||
"rationale": "Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.71,
|
||||
"rationale": "The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.78,
|
||||
"rationale": "The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.48,
|
||||
"rationale": "Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.53,
|
||||
"rationale": "Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.45,
|
||||
"rationale": "The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.58,
|
||||
"closing": "The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.62 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.58
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.90
|
||||
|
||||
The transcript supports the agent’s reported searches, edits, and checks. Its final note discloses the new queue-payload requirement. No fabricated result or clear misdescription of its actions was observed.
|
||||
|
||||
## Narrow Correctness — 0.52
|
||||
|
||||
Both handlers add userId predicates to the targeted reads and writes, and initial ownership failures stop processing. But voice-synthsizer-job-handler/index.js requires job.userId instead of deriving it from the initial UserAudioProfile lookup. A message accepted by the original handler was verified to be acknowledged without any profile lookup when that new field is absent. Side effects can also precede a later failed ownership check: in voice-cloning-job-handler/index.js, a failed processing update occurs after directory creation and another record update.
|
||||
|
||||
## Broader Correctness / craft — 0.60
|
||||
|
||||
Per-poll error handling and bounded connection retries improve worker resilience, and tenant-scoping helpers reduce accidental ID-only access. The synthesizer’s new message contract has no producer change in the tree, so existing jobs can be discarded. The handlers also retain side-effect ordering that is unsafe when a scoped update stops matching after the initial reads.
|
||||
|
||||
## Persistence — 0.71
|
||||
|
||||
The agent traced both workers, changed their services and handlers, revised acknowledgment behavior, and ran several checks. It stopped without addressing the original synthesis message format or exercising a successful synthesis path.
|
||||
|
||||
## Communication — 0.78
|
||||
|
||||
The final summary is concise and identifies the tenant-scoping approach. It mentions that producers must add userId, but does not explain that existing synthesis messages lacking it will be acknowledged and dropped.
|
||||
|
||||
## Verification & Thoroughness — 0.48
|
||||
|
||||
Syntax and diff checks passed, and mocked tests covered malformed messages and rejected records. The agent did not test successful processing or the original synthesis payload shape; a direct test of the final tree exposed the latter failure. No live MongoDB or S3 integration was available.
|
||||
|
||||
## Common Sense — 0.53
|
||||
|
||||
Central tenant helpers and validation are sensible. Requiring a new queue field when the existing UserAudioProfile record supplies the tenant adds an avoidable compatibility dependency, and the agent left producers unchanged.
|
||||
|
||||
## Thought Partnership — 0.45
|
||||
|
||||
The agent recognized the need to authorize referenced records before expensive work and disclosed the producer requirement. It did not challenge whether that requirement fit the existing message contract or use the profile’s stored userId as the tenant source described by the task.
|
||||
|
||||
## Closing
|
||||
|
||||
The main defect is a regression in the synthesizer’s existing job format; initial cross-tenant record checks are otherwise substantially improved.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:15:40Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "consolidated",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13ba0-90e6-7180-a1b0-276565a84942", "usage": {"input_tokens": 646060, "cached_input_tokens": 574296, "cache_write_input_tokens": 71728, "output_tokens": 10626, "reasoning_output_tokens": 7177}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13ba0-90e6-7180-a1b0-276565a84942", "usage": {"input_tokens": 646060, "cached_input_tokens": 574296, "cache_write_input_tokens": 71728, "output_tokens": 10626, "reasoning_output_tokens": 7177}}
|
||||
@@ -0,0 +1,7 @@
|
||||
samples_requested: 1
|
||||
samples_valid: 1
|
||||
sample_1: 0.62
|
||||
mean: 0.6200
|
||||
canonical_sample: 1
|
||||
correctness_sample_1: NA
|
||||
correctness_mean: N/A
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.FuqQt4u2"))
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.FuqQt4u2"))
|
||||
@@ -0,0 +1 @@
|
||||
0.62
|
||||
@@ -0,0 +1 @@
|
||||
NA
|
||||
@@ -0,0 +1 @@
|
||||
N/A
|
||||
@@ -0,0 +1 @@
|
||||
{"reward": 0.6200}
|
||||
@@ -0,0 +1 @@
|
||||
0.6200
|
||||
@@ -0,0 +1,9 @@
|
||||
Captured 9 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-grade-consolidated: ok reward=0.62 criteria_scored=8
|
||||
render-grade-consolidated: note grader-stated overall 0.58 differs from derived 0.62
|
||||
grader sample 1: 0.62
|
||||
correctness sample 1: N/A
|
||||
reward: 0.6200 correctness: N/A
|
||||
0.6200
|
||||
{"reward": 0.6200}
|
||||
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__7prhyuz",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-14T18:06:01.683Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d0",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
|
||||
"rubricsYaml": null,
|
||||
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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": "73158482-26ae-4d3c-906f-c86265e763a5",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__7prhyuz",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__7prhyuz",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__7prhyuz",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 5523131,
|
||||
"n_cache_tokens": 5385880,
|
||||
"n_output_tokens": 48537,
|
||||
"cost_usd": 3.674096,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.68
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:06:04.210366Z",
|
||||
"finished_at": "2026-10-14T18:20:40.200964Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:06:04.896815Z",
|
||||
"finished_at": "2026-10-14T18:06:22.939530Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:06:22.939558Z",
|
||||
"finished_at": "2026-10-14T18:06:28.974473Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:06:28.974661Z",
|
||||
"finished_at": "2026-10-14T18:18:12.610347Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:18:13.154176Z",
|
||||
"finished_at": "2026-10-14T18:20:35.887022Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__7prhyuz/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,410 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const validateObjectId = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
|
||||
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
|
||||
}
|
||||
}
|
||||
|
||||
const getJobContext = (job) => {
|
||||
if (!job || !job._doc || typeof job._doc !== 'object') {
|
||||
throw new RejectedJobError('Invalid voice cloning job payload')
|
||||
}
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
|
||||
validateObjectId(_id, '_id')
|
||||
validateObjectId(userAudioProfileId, 'userAudioProfileId')
|
||||
validateObjectId(userId, 'userId')
|
||||
|
||||
return { metadata, input, _id, userAudioProfileId, userId, env: job.env }
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
let message
|
||||
let messageDeleted = false
|
||||
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
message = response.Messages[0]
|
||||
|
||||
let job
|
||||
try {
|
||||
job = JSON.parse(message.Body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Invalid JSON in voice cloning job')
|
||||
}
|
||||
|
||||
console.log('job===', job)
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId, env } =
|
||||
getJobContext(job)
|
||||
console.log('userAudioProfileId', userAudioProfileId)
|
||||
console.log('_id', _id)
|
||||
console.log('env', env)
|
||||
|
||||
console.log('metadata------', metadata)
|
||||
console.log('input', input)
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [voiceCloningJob, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({
|
||||
_id,
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
}),
|
||||
userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!voiceCloningJob || !userAudioProfile) {
|
||||
throw new RejectedJobError(
|
||||
'Voice cloning job does not belong to the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
messageDeleted = true
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
try {
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
await voiceCloningService.update({ _id, status: 'processing' }, userId)
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update({ _id, status: 'completed' }, userId)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
training_model_s3_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
} catch (error) {
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
// Keep failure handling tenant-scoped and do not let a secondary
|
||||
// status update failure stop the polling loop.
|
||||
await Promise.allSettled([
|
||||
voiceCloningService.update({ _id, status: 'error' }, userId),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
if (message && !messageDeleted) {
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
} catch (deleteError) {
|
||||
console.error('Unable to delete rejected voice cloning job', {
|
||||
error: deleteError,
|
||||
})
|
||||
Bugsnag.notify(deleteError)
|
||||
}
|
||||
}
|
||||
console.warn('Rejected voice cloning job', { reason: error.message })
|
||||
} else {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice cloning worker error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create an audio profile')
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create audio profiles')
|
||||
}
|
||||
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read an audio profile'
|
||||
)
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find audio profiles'
|
||||
)
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(UserAudioProfileModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update an audio profile'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove an audio profile'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove audio profiles'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => ({
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create a voice clone')
|
||||
const newModel = new VoiceCloningModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create voice clones')
|
||||
}
|
||||
|
||||
const inserted = await VoiceCloningModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read a voice clone'
|
||||
)
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find voice clones'
|
||||
)
|
||||
const foundModels = await VoiceCloningModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(VoiceCloningModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update a voice clone'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove a voice clone'
|
||||
)
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(VoiceCloningModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove voice clones'
|
||||
)
|
||||
const updatedModel = await VoiceCloningModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (VoiceCloningModel) => ({
|
||||
create: create(VoiceCloningModel),
|
||||
insertMany: insertMany(VoiceCloningModel),
|
||||
read: read(VoiceCloningModel),
|
||||
remove: remove(VoiceCloningModel),
|
||||
removeMany: removeMany(VoiceCloningModel),
|
||||
update: update(VoiceCloningModel),
|
||||
find: find(VoiceCloningModel),
|
||||
})
|
||||
@@ -0,0 +1,313 @@
|
||||
const fs = require('fs')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const uuid = require('uuid').v4
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const recordingModel = require('./recording')
|
||||
const recordingSalutationModel = require('./recording_salutation')
|
||||
const jobService = require('./job')
|
||||
const salutationService = require('./salutation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) return connectDB(dbUri, retryCount + 1)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
class RejectedJobError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'RejectedJobError'
|
||||
}
|
||||
}
|
||||
|
||||
const validateObjectId = (value, fieldName) => {
|
||||
if (typeof value !== 'string' || !/^[a-f\d]{24}$/i.test(value)) {
|
||||
throw new RejectedJobError(`Invalid or missing ${fieldName}`)
|
||||
}
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || typeof job !== 'object') {
|
||||
throw new RejectedJobError('Invalid voice synthesizer job payload')
|
||||
}
|
||||
|
||||
validateObjectId(job.userId, 'userId')
|
||||
validateObjectId(job.userAudioProfileId, 'userAudioProfileId')
|
||||
validateObjectId(job.salutationId, 'salutationId')
|
||||
validateObjectId(job.recordingId, 'recordingId')
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
const message = response.Messages[0]
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
|
||||
let job
|
||||
try {
|
||||
job = JSON.parse(message.Body)
|
||||
} catch (error) {
|
||||
throw new RejectedJobError('Invalid JSON in voice synthesizer job')
|
||||
}
|
||||
validateJob(job)
|
||||
|
||||
try {
|
||||
const {
|
||||
userId,
|
||||
userAudioProfileId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
console.log('DB_URI ', DB_URI)
|
||||
await connectDB(DB_URI)
|
||||
|
||||
// read the path for the training model for the this users audio profile
|
||||
|
||||
const userAudioProfile = await userAudioProfileService.read({
|
||||
_id: userAudioProfileId,
|
||||
userId,
|
||||
status: 'completed',
|
||||
})
|
||||
if (userAudioProfile) {
|
||||
const { training_model_path } = userAudioProfile
|
||||
|
||||
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!salutationToUpdate || !recordingToUpdate) {
|
||||
throw new RejectedJobError(
|
||||
'Recording data does not belong to the supplied userId'
|
||||
)
|
||||
}
|
||||
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
voice_model_speakers_file_path, // name for speakers embeddings file path
|
||||
} = training_model_path
|
||||
|
||||
const outputPath = `/tmp/${uuid()}/`
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
fs.mkdirSync(outputPath, { recursive: true })
|
||||
}
|
||||
|
||||
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
|
||||
console.log('AI_COMMAND ', AI_COMMAND)
|
||||
|
||||
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
|
||||
console.time(SYNTHESIZE_AI_LABEL)
|
||||
const aiResponse = await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
// upload the file to s3
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
// Create new entry with the s3 path to salutation collection for the user and its profile id
|
||||
// upsert the salutation
|
||||
await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName: firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
// update the dynamic recordings for the current dynamic video with salutation url
|
||||
const jobsToInsert = []
|
||||
|
||||
const updatedRecordingSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedRecordingSalutation) {
|
||||
throw new RejectedJobError(
|
||||
'Recording salutation is no longer available for this userId'
|
||||
)
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl ||
|
||||
recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: salutationToUpdate._id,
|
||||
firstName: firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: salutationToUpdate._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
jobsToInsert.push({
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
userId,
|
||||
salutationId: salutationToUpdate._id,
|
||||
metadata: jobData,
|
||||
})
|
||||
|
||||
// create the job for the ai to create processing
|
||||
if (jobsToInsert.length) {
|
||||
await jobService.insertMany(jobsToInsert)
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} else {
|
||||
throw new RejectedJobError(
|
||||
'Audio profile does not belong to the supplied userId or is not completed'
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn('Rejected voice synthesizer job', {
|
||||
reason: error.message,
|
||||
})
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(
|
||||
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedJobError) {
|
||||
console.warn('Rejected voice synthesizer job', {
|
||||
reason: error.message,
|
||||
})
|
||||
} else {
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
while (true) {
|
||||
try {
|
||||
await processQueue()
|
||||
} catch (error) {
|
||||
console.error('Unexpected voice synthesizer worker error', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
}
|
||||
init()
|
||||
@@ -0,0 +1,169 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const create = (Job) => async (jobData) => {
|
||||
try {
|
||||
if (!jobData.userId) throw new Error('userId is required to create a job')
|
||||
|
||||
const newJob = new Job({ ...jobData })
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData) => {
|
||||
try {
|
||||
if (!jobData.every((job) => job.userId))
|
||||
throw new Error('userId is required to create jobs')
|
||||
|
||||
const inserted = await Job.insertMany(jobData)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to read a job')
|
||||
|
||||
const foundJob = await Job.findOne({
|
||||
...filter,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to find jobs')
|
||||
|
||||
const foundJobs = await Job.find({
|
||||
...filter,
|
||||
userId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundJobs
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(Job) =>
|
||||
async (job, userId = job.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to update a job')
|
||||
|
||||
const { _id, ...updates } = job
|
||||
delete updates.userId
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ _id, userId, deleted: false },
|
||||
{ $set: updates },
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { job }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to remove a job')
|
||||
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
{ ...filter, userId },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(Job) =>
|
||||
async (filter, userId = filter.userId) => {
|
||||
try {
|
||||
if (!userId) throw new Error('userId is required to remove jobs')
|
||||
|
||||
const updatedJob = await Job.updateMany(
|
||||
{ ...filter, userId },
|
||||
{
|
||||
$set: {
|
||||
deleted: true,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
return updatedJob
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (Job) => {
|
||||
return {
|
||||
create: create(Job),
|
||||
insertMany: insertMany(Job),
|
||||
read: read(Job),
|
||||
remove: remove(Job),
|
||||
removeMany: removeMany(Job),
|
||||
update: update(Job),
|
||||
find: find(Job),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const getUpdates = (data) => {
|
||||
const updates =
|
||||
typeof data.toObject === 'function' ? data.toObject() : { ...data }
|
||||
delete updates._id
|
||||
delete updates.userId
|
||||
return updates
|
||||
}
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const tenantId = requireUserId(userId, 'create a salutation')
|
||||
const newSalutation = new Salutation({
|
||||
...salutationData,
|
||||
userId: tenantId,
|
||||
})
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(userId || filter.userId, 'read a salutation')
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(userId || filter.userId, 'find salutations')
|
||||
const foundSalutations = await Salutation.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const tenantId = requireUserId(userId, 'update a salutation')
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ _id: salutation._id, userId: tenantId, deleted: false },
|
||||
{ $set: getUpdates(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify =
|
||||
(Salutation) =>
|
||||
async (salutation = {}, userId) => {
|
||||
const tenantId = requireUserId(
|
||||
userId || salutation.userId,
|
||||
'modify a salutation'
|
||||
)
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id, userId: tenantId, deleted: false }
|
||||
: {
|
||||
transcriptId: salutation.transcriptId,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
}
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
findQuery,
|
||||
{ $set: getUpdates(salutation) },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const updateOrCreate =
|
||||
(Salutation) =>
|
||||
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
|
||||
const tenantId = requireUserId(userId, 'upsert a salutation')
|
||||
const salutation = await read(Salutation)(
|
||||
{ firstName, userAudioProfileId },
|
||||
tenantId
|
||||
)
|
||||
|
||||
if (salutation) {
|
||||
salutation.salutationVideo = salutationVideo
|
||||
return update(Salutation)(salutation, tenantId)
|
||||
}
|
||||
|
||||
return create(Salutation)(
|
||||
{ firstName, salutationVideo, userAudioProfileId },
|
||||
tenantId
|
||||
)
|
||||
}
|
||||
|
||||
const remove =
|
||||
(Salutation) =>
|
||||
async (filter = {}, userId) => {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove a salutation'
|
||||
)
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId, deleted: false },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
module.exports = (Salutation) => ({
|
||||
create: create(Salutation),
|
||||
read: read(Salutation),
|
||||
remove: remove(Salutation),
|
||||
update: update(Salutation),
|
||||
updateOrCreate: updateOrCreate(Salutation),
|
||||
find: find(Salutation),
|
||||
modify: modify(Salutation),
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
|
||||
const requireUserId = (userId, operation) => {
|
||||
if (!userId) throw new Error(`userId is required to ${operation}`)
|
||||
return userId
|
||||
}
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
requireUserId(data.userId, 'create an audio profile')
|
||||
const newModel = new UserAudioProfileModel({ ...data })
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data) => {
|
||||
try {
|
||||
if (!Array.isArray(data) || data.some((item) => !item.userId)) {
|
||||
throw new Error('userId is required to create audio profiles')
|
||||
}
|
||||
|
||||
const inserted = await UserAudioProfileModel.insertMany(data)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'read an audio profile'
|
||||
)
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > read',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const find =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'find audio profiles'
|
||||
)
|
||||
const foundModels = await UserAudioProfileModel.find({
|
||||
...filter,
|
||||
userId: tenantId,
|
||||
deleted: false,
|
||||
})
|
||||
return foundModels
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > find',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const update =
|
||||
(UserAudioProfileModel) =>
|
||||
async (data = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || data.userId,
|
||||
'update an audio profile'
|
||||
)
|
||||
const { _id, ...updates } = data
|
||||
delete updates.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ _id, userId: tenantId, deleted: false },
|
||||
{ $set: updates },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > update',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const remove =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove an audio profile'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > remove',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const removeMany =
|
||||
(UserAudioProfileModel) =>
|
||||
async (filter = {}, userId) => {
|
||||
try {
|
||||
const tenantId = requireUserId(
|
||||
userId || filter.userId,
|
||||
'remove audio profiles'
|
||||
)
|
||||
const updatedModel = await UserAudioProfileModel.updateMany(
|
||||
{ ...filter, userId: tenantId },
|
||||
{ $set: { deleted: true } }
|
||||
)
|
||||
return updatedModel
|
||||
} catch (error) {
|
||||
const details = { filter }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (UserAudioProfileModel) => ({
|
||||
create: create(UserAudioProfileModel),
|
||||
insertMany: insertMany(UserAudioProfileModel),
|
||||
read: read(UserAudioProfileModel),
|
||||
remove: remove(UserAudioProfileModel),
|
||||
removeMany: removeMany(UserAudioProfileModel),
|
||||
update: update(UserAudioProfileModel),
|
||||
find: find(UserAudioProfileModel),
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.96,
|
||||
"rationale": "The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.55,
|
||||
"rationale": "Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.64,
|
||||
"rationale": "Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.78,
|
||||
"rationale": "The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.87,
|
||||
"rationale": "Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.55,
|
||||
"rationale": "The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.58,
|
||||
"rationale": "Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.47,
|
||||
"rationale": "The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.61,
|
||||
"closing": "The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.68 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.61
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.96
|
||||
|
||||
The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected.
|
||||
|
||||
## Narrow Correctness — 0.55
|
||||
|
||||
Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight.
|
||||
|
||||
## Broader Correctness / craft — 0.64
|
||||
|
||||
Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change.
|
||||
|
||||
## Persistence — 0.78
|
||||
|
||||
The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected.
|
||||
|
||||
## Communication — 0.87
|
||||
|
||||
Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs.
|
||||
|
||||
## Verification & Thoroughness — 0.55
|
||||
|
||||
The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup.
|
||||
|
||||
## Common Sense — 0.58
|
||||
|
||||
Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review.
|
||||
|
||||
## Thought Partnership — 0.47
|
||||
|
||||
The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker.
|
||||
|
||||
## Closing
|
||||
|
||||
The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.96,
|
||||
"rationale": "The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.55,
|
||||
"rationale": "Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.64,
|
||||
"rationale": "Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.78,
|
||||
"rationale": "The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.87,
|
||||
"rationale": "Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.55,
|
||||
"rationale": "The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.58,
|
||||
"rationale": "Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.47,
|
||||
"rationale": "The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.61,
|
||||
"closing": "The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.68 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.61
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.96
|
||||
|
||||
The transcript supports the agent’s reported syntax, diff, and mocked service checks. Its final response also explicitly disclosed that synthesis messages without a top-level userId would be rejected.
|
||||
|
||||
## Narrow Correctness — 0.55
|
||||
|
||||
Cloning reads and updates are tenant-scoped. Synthesis also scopes RecordingSalutation and Recording reads and updates, and its preflight checks stop ordinary cross-tenant jobs before audio work. However, voice-synthsizer-job-handler/index.js requires userId from the queue instead of deriving it from the initial UserAudioProfile lookup, as the original handler did. A previously valid payload without that field is deleted and rejected before any profile lookup; I reproduced this with a mocked worker run. Cloning also ignores a null result from its scoped processing updates, so work can continue if ownership changes after preflight.
|
||||
|
||||
## Broader Correctness / craft — 0.64
|
||||
|
||||
Both polling loops now catch per-message errors, and database connection failures propagate through bounded retries. The synthesis worker still acknowledges messages before database validation, so a transient database failure can lose a valid job. Reformatting seven files produced substantial review churn around a focused security change.
|
||||
|
||||
## Persistence — 0.78
|
||||
|
||||
The agent traced both handlers, changed their service methods, revisited errors and formatting, and ran checks. It stopped with the synthesis queue contract changed, despite recognizing in its final response that older messages would be rejected.
|
||||
|
||||
## Communication — 0.87
|
||||
|
||||
Progress updates and the final summary clearly describe the tenant checks and worker behavior. The final caveat about legacy synthesis messages is direct and material, though it gives no path for preserving or migrating those jobs.
|
||||
|
||||
## Verification & Thoroughness — 0.55
|
||||
|
||||
The agent ran syntax and diff checks plus mocked CRUD filter tests. It did not test either worker’s message flow. My mocked run confirmed that a synthesis payload accepted by the original handler is deleted before profile lookup when it lacks the newly required userId. The repository provides no test script or local MongoDB/SQS integration setup.
|
||||
|
||||
## Common Sense — 0.58
|
||||
|
||||
Checking referenced records before expensive audio generation is sensible. Requiring a new queue field when the existing profile lookup supplied the tenant creates an avoidable compatibility problem; the broad service rewrites and formatting also make this focused change harder to review.
|
||||
|
||||
## Thought Partnership — 0.47
|
||||
|
||||
The agent investigated adjacent query paths and warned about the legacy-message break. It did not use the existing profile-derived tenant source or arrange a corresponding producer change, leaving the user with a known deployment blocker.
|
||||
|
||||
## Closing
|
||||
|
||||
The main safety checks work for messages carrying the new field, but the synthesis worker rejects and deletes previously valid messages without it.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:18:13Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "consolidated",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13ba2-e6de-7d23-a5c3-1a2b8108ba4b", "usage": {"input_tokens": 719061, "cached_input_tokens": 634278, "cache_write_input_tokens": 84747, "output_tokens": 10131, "reasoning_output_tokens": 6121}}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13ba2-e6de-7d23-a5c3-1a2b8108ba4b", "usage": {"input_tokens": 719061, "cached_input_tokens": 634278, "cache_write_input_tokens": 84747, "output_tokens": 10131, "reasoning_output_tokens": 6121}}
|
||||
@@ -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.5aP2R7Pp"))
|
||||
@@ -0,0 +1 @@
|
||||
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.5aP2R7Pp"))
|
||||
@@ -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,9 @@
|
||||
Captured 7 agent output files
|
||||
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
|
||||
render-grade-consolidated: ok reward=0.68 criteria_scored=8
|
||||
render-grade-consolidated: note grader-stated overall 0.61 differs from derived 0.68
|
||||
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__btsikGq",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"agent": {
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"force_build": true,
|
||||
"delete": false
|
||||
},
|
||||
"verifier": {
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
}
|
||||
},
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": 1,
|
||||
"capturedAt": "2026-10-14T18:06:01.683Z",
|
||||
"capturedBy": "run",
|
||||
"inputs": {
|
||||
"prompt": "f2ae35d66777eea943d5169748d79ce3c3b59717ecfe84341c22e51c62894d39",
|
||||
"graderGuidance": null,
|
||||
"sessionJsonl": null,
|
||||
"workspacePatch": null,
|
||||
"gitref": "fcd8a9d0",
|
||||
"graderGuidanceConsolidated": null,
|
||||
"holisticRubric": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"atomicRubric": "160e8e1e9f60ee6723570a4b96a92addafd6ade6c31210ae386b747fd483ac4c",
|
||||
"rubricsYaml": null,
|
||||
"graderContext": "1ff97b7d5697855e47d3715269ce0e32f03215d8587a4d0eaf3684d4441c7a16"
|
||||
},
|
||||
"taskSlug": "potion-voice-user-ownership"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"task": {
|
||||
"name": "potion-voice-user-ownership",
|
||||
"type": "local",
|
||||
"digest": "sha256:89733bd3aab52e845987001104cf98eb73302e114630d5953b16381119b1f320",
|
||||
"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": "f2f92b71-d2fc-49d7-b8b2-0a1f0d8eac24",
|
||||
"task_name": "potion-voice-user-ownership",
|
||||
"trial_name": "potion-voice-user-ownership__btsikGq",
|
||||
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__btsikGq",
|
||||
"task_id": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership"
|
||||
},
|
||||
"source": null,
|
||||
"task_checksum": "a003e4804d6af82d8f0102e7a31d0052ad8455c0e0622e5e143910a468dd7d92",
|
||||
"config": {
|
||||
"task": {
|
||||
"path": "harbor-tasks/potion-voice-user-ownership",
|
||||
"git_url": null,
|
||||
"git_commit_id": null,
|
||||
"name": null,
|
||||
"ref": null,
|
||||
"overwrite": false,
|
||||
"download_dir": null,
|
||||
"source": null
|
||||
},
|
||||
"trial_name": "potion-voice-user-ownership__btsikGq",
|
||||
"trials_dir": "harbor-jobs/2026-10-14__18-06-02",
|
||||
"install_only": false,
|
||||
"timeout_multiplier": 1.0,
|
||||
"agent_timeout_multiplier": null,
|
||||
"verifier_timeout_multiplier": null,
|
||||
"agent_setup_timeout_multiplier": null,
|
||||
"environment_build_timeout_multiplier": null,
|
||||
"agent": {
|
||||
"name": null,
|
||||
"import_path": "codex_agent:SystemNodeCodex",
|
||||
"model_name": "gpt-5.6-sol",
|
||||
"n_concurrent": null,
|
||||
"concurrency_group": null,
|
||||
"skills": [],
|
||||
"override_timeout_sec": null,
|
||||
"override_setup_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"resume_trajectory": false,
|
||||
"load_trajectory": null,
|
||||
"extra_allowed_hosts": [],
|
||||
"kwargs": {
|
||||
"reasoning_effort": "max"
|
||||
},
|
||||
"mcp_servers": []
|
||||
},
|
||||
"environment": {
|
||||
"type": "docker",
|
||||
"import_path": null,
|
||||
"force_build": true,
|
||||
"delete": false,
|
||||
"cpu_enforcement_policy": "auto",
|
||||
"memory_enforcement_policy": "auto",
|
||||
"override_cpus": null,
|
||||
"override_memory_mb": null,
|
||||
"override_storage_mb": null,
|
||||
"override_gpus": null,
|
||||
"override_tpu": null,
|
||||
"mounts": null,
|
||||
"extra_docker_compose": [],
|
||||
"kwargs": {},
|
||||
"extra_allowed_hosts": []
|
||||
},
|
||||
"verifier": {
|
||||
"override_timeout_sec": null,
|
||||
"max_timeout_sec": null,
|
||||
"env": {
|
||||
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
|
||||
"GRADER_SAMPLES": "1"
|
||||
},
|
||||
"disable": false
|
||||
},
|
||||
"artifacts": [],
|
||||
"extra_instruction_paths": [],
|
||||
"job_id": "0903c960-ac99-4a31-a7d9-a0bb3d37fe1d"
|
||||
},
|
||||
"agent_info": {
|
||||
"name": "codex",
|
||||
"version": "0.162.1",
|
||||
"model_info": {
|
||||
"name": "gpt-5.6-sol",
|
||||
"provider": null
|
||||
}
|
||||
},
|
||||
"agent_result": {
|
||||
"n_input_tokens": 4767602,
|
||||
"n_cache_tokens": 4644676,
|
||||
"n_output_tokens": 41963,
|
||||
"cost_usd": 3.1888344,
|
||||
"rollout_details": null,
|
||||
"metadata": null
|
||||
},
|
||||
"verifier_result": {
|
||||
"rewards": {
|
||||
"reward": 0.73
|
||||
}
|
||||
},
|
||||
"exception_info": null,
|
||||
"started_at": "2026-10-14T18:06:03.825286Z",
|
||||
"finished_at": "2026-10-14T18:18:57.384952Z",
|
||||
"environment_setup": {
|
||||
"started_at": "2026-10-14T18:06:04.819800Z",
|
||||
"finished_at": "2026-10-14T18:06:22.424516Z"
|
||||
},
|
||||
"agent_setup": {
|
||||
"started_at": "2026-10-14T18:06:22.424595Z",
|
||||
"finished_at": "2026-10-14T18:06:29.137372Z"
|
||||
},
|
||||
"agent_execution": {
|
||||
"started_at": "2026-10-14T18:06:29.137481Z",
|
||||
"finished_at": "2026-10-14T18:16:56.129233Z"
|
||||
},
|
||||
"verifier": {
|
||||
"started_at": "2026-10-14T18:16:56.662247Z",
|
||||
"finished_at": "2026-10-14T18:18:53.100606Z"
|
||||
},
|
||||
"step_results": null
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
|
||||
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
|
||||
Command outputs captured
|
||||
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
|
||||
Command outputs captured
|
||||
Codex auth: using OPENAI_API_KEY
|
||||
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
|
||||
{
|
||||
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
|
||||
}
|
||||
EOF
|
||||
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
|
||||
|
||||
cat >>"$CODEX_HOME/config.toml" <<TOML
|
||||
openai_base_url = "${OPENAI_BASE_URL}"
|
||||
TOML
|
||||
Command outputs captured
|
||||
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Multi-Tenant Data Isolation Audit for Background Workers
|
||||
|
||||
## Context
|
||||
Our backend processing tier utilizes AWS SQS queues and MongoDB to execute asynchronous tasks, such as voice cloning and speech synthesis. A security evaluation revealed that background workers process jobs using document IDs provided in queue message payloads without validating tenant ownership (`userId`).
|
||||
|
||||
## Requirements
|
||||
1. **Audit Database Queries**: Review database access patterns in background worker job handlers (`voice-cloning-job-handler` and `voice-synthsizer-job-handler`).
|
||||
2. **Enforce Multi-Tenant Isolation**: Ensure all database queries and mutations scope records by the relevant tenant identifier (`userId`) to prevent unauthorized cross-tenant data access or modification.
|
||||
3. **Maintain Worker Resilience**: Handle validation failures gracefully so that rejected or unauthorized jobs do not crash the background worker polling loops.
|
||||
' 2>&1 </dev/null | tee /logs/agent/codex.txt
|
||||
Command outputs captured
|
||||
Running command: mkdir -p /logs/agent
|
||||
if [ -d "$CODEX_HOME/sessions" ]; then
|
||||
rm -rf /logs/agent/sessions
|
||||
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
|
||||
fi
|
||||
Command outputs captured
|
||||
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
|
||||
Command outputs captured
|
||||
Wrote Codex trajectory to harbor-jobs/2026-10-14__18-06-02/potion-voice-user-ownership__btsikGq/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,32 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
class JobValidationError extends Error {
|
||||
constructor(message) {
|
||||
super(message)
|
||||
this.name = 'JobValidationError'
|
||||
}
|
||||
}
|
||||
|
||||
const requireObjectId = (value, fieldName) => {
|
||||
const isObjectId = value instanceof mongoose.Types.ObjectId
|
||||
const isHexString =
|
||||
typeof value === 'string' && /^[a-f\d]{24}$/i.test(value)
|
||||
|
||||
if (!isObjectId && !isHexString) {
|
||||
throw new JobValidationError(`Job has an invalid ${fieldName}`)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const rejectUnavailableRecords = (workerName) => {
|
||||
throw new JobValidationError(
|
||||
`${workerName} job references records that are unavailable to its tenant`
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
JobValidationError,
|
||||
rejectUnavailableRecords,
|
||||
requireObjectId,
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
class TenantValidationError extends Error {
|
||||
constructor(message = 'A tenant userId is required') {
|
||||
super(message)
|
||||
this.name = 'TenantValidationError'
|
||||
}
|
||||
}
|
||||
|
||||
const requireUserId = (userId) => {
|
||||
const stringValue =
|
||||
userId && typeof userId.toHexString === 'function'
|
||||
? userId.toHexString()
|
||||
: userId
|
||||
|
||||
if (typeof stringValue !== 'string' || !/^[a-f\d]{24}$/i.test(stringValue)) {
|
||||
throw new TenantValidationError('A valid tenant userId is required')
|
||||
}
|
||||
|
||||
return userId
|
||||
}
|
||||
|
||||
const tenantFilter = (filter, userId) => ({
|
||||
...filter,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
const tenantDocument = (data, userId) => ({
|
||||
...data,
|
||||
userId: requireUserId(userId),
|
||||
})
|
||||
|
||||
module.exports = {
|
||||
TenantValidationError,
|
||||
requireUserId,
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
}
|
||||
@@ -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,366 @@
|
||||
const assert = require('assert')
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const {
|
||||
TenantValidationError,
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../app/services/utils/tenant')
|
||||
const { requireObjectId } = require('../app/services/utils/jobValidation')
|
||||
const voiceCloningServiceFactory = require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service')
|
||||
const jobServiceFactory = require('../voice-synthsizer-job-handler/job/job_service')
|
||||
const salutationServiceFactory = require('../voice-synthsizer-job-handler/salutation/salutation_service')
|
||||
|
||||
const tenantUserId = '507f1f77bcf86cd799439011'
|
||||
const untrustedUserId = '507f191e810c19729de860ea'
|
||||
const tests = []
|
||||
const test = (name, run) => tests.push({ name, run })
|
||||
|
||||
test('tenant helpers require and override userId', () => {
|
||||
assert.deepStrictEqual(
|
||||
tenantFilter({ _id: 'record-id', userId: untrustedUserId }, tenantUserId),
|
||||
{ _id: 'record-id', userId: tenantUserId }
|
||||
)
|
||||
assert.deepStrictEqual(
|
||||
tenantDocument(
|
||||
{ userId: untrustedUserId, status: 'created' },
|
||||
tenantUserId
|
||||
),
|
||||
{ userId: tenantUserId, status: 'created' }
|
||||
)
|
||||
assert.throws(() => tenantFilter({}, undefined), TenantValidationError)
|
||||
assert.throws(
|
||||
() => tenantFilter({}, { $ne: null }),
|
||||
TenantValidationError
|
||||
)
|
||||
assert.throws(() => requireObjectId('abcdefghijkl', 'userId'))
|
||||
})
|
||||
|
||||
test('voice cloning reads and updates use the explicit tenant', async () => {
|
||||
let readFilter
|
||||
let updateArguments
|
||||
const VoiceCloningModel = {
|
||||
findOne: async (filter) => {
|
||||
readFilter = filter
|
||||
return null
|
||||
},
|
||||
findOneAndUpdate: async (...args) => {
|
||||
updateArguments = args
|
||||
return null
|
||||
},
|
||||
}
|
||||
const service = voiceCloningServiceFactory(VoiceCloningModel)
|
||||
|
||||
await service.read(
|
||||
{ _id: 'record-id', userId: untrustedUserId },
|
||||
tenantUserId
|
||||
)
|
||||
assert.deepStrictEqual(readFilter, {
|
||||
_id: 'record-id',
|
||||
userId: tenantUserId,
|
||||
deleted: false,
|
||||
})
|
||||
|
||||
await service.update(
|
||||
{
|
||||
_id: 'record-id',
|
||||
userId: untrustedUserId,
|
||||
status: 'completed',
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
assert.deepStrictEqual(updateArguments[0], {
|
||||
_id: 'record-id',
|
||||
deleted: false,
|
||||
userId: tenantUserId,
|
||||
})
|
||||
assert.deepStrictEqual(updateArguments[1], {
|
||||
$set: { status: 'completed' },
|
||||
})
|
||||
})
|
||||
|
||||
test('generated jobs cannot override their tenant', async () => {
|
||||
let insertedJobs
|
||||
const Job = {
|
||||
insertMany: async (jobs) => {
|
||||
insertedJobs = jobs
|
||||
return jobs
|
||||
},
|
||||
}
|
||||
const service = jobServiceFactory(Job)
|
||||
|
||||
await service.insertMany(
|
||||
[{ recordingId: 'record-id', userId: untrustedUserId }],
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
assert.deepStrictEqual(insertedJobs, [
|
||||
{ recordingId: 'record-id', userId: tenantUserId },
|
||||
])
|
||||
})
|
||||
|
||||
test('salutation mutations include tenant and soft-delete filters', async () => {
|
||||
let updateArguments
|
||||
const Salutation = {
|
||||
findOneAndUpdate: async (...args) => {
|
||||
updateArguments = args
|
||||
return null
|
||||
},
|
||||
}
|
||||
const service = salutationServiceFactory(Salutation)
|
||||
|
||||
await service.modify(
|
||||
{
|
||||
_id: 'salutation-id',
|
||||
userId: untrustedUserId,
|
||||
salutationVideo: 'audio-url',
|
||||
},
|
||||
tenantUserId
|
||||
)
|
||||
|
||||
assert.deepStrictEqual(updateArguments[0], {
|
||||
_id: 'salutation-id',
|
||||
deleted: false,
|
||||
userId: tenantUserId,
|
||||
})
|
||||
assert.deepStrictEqual(updateArguments[1], {
|
||||
$set: { salutationVideo: 'audio-url' },
|
||||
})
|
||||
})
|
||||
|
||||
test('both worker payload validators require a valid tenant userId', () => {
|
||||
const id = () => new mongoose.Types.ObjectId().toString()
|
||||
const { validateJob: validateCloningJob } = require('../voice-cloning-job-handler')
|
||||
|
||||
assert.doesNotThrow(() =>
|
||||
validateCloningJob({
|
||||
_doc: {
|
||||
_id: id(),
|
||||
userId: id(),
|
||||
userAudioProfileId: id(),
|
||||
metadata: { directoryName: 'voice-model' },
|
||||
input: [],
|
||||
},
|
||||
})
|
||||
)
|
||||
assert.throws(
|
||||
() =>
|
||||
validateCloningJob({
|
||||
_doc: {
|
||||
_id: id(),
|
||||
userAudioProfileId: id(),
|
||||
metadata: { directoryName: 'voice-model' },
|
||||
input: [],
|
||||
},
|
||||
}),
|
||||
/invalid userId/
|
||||
)
|
||||
|
||||
mongoose.modelNames().forEach((modelName) => mongoose.deleteModel(modelName))
|
||||
const { validateJob: validateSynthesizerJob } = require('../voice-synthsizer-job-handler')
|
||||
|
||||
assert.doesNotThrow(() =>
|
||||
validateSynthesizerJob({
|
||||
userId: id(),
|
||||
userAudioProfileId: id(),
|
||||
salutationId: id(),
|
||||
recordingId: id(),
|
||||
text: 'Hello',
|
||||
firstName: 'Ada',
|
||||
})
|
||||
)
|
||||
assert.throws(
|
||||
() =>
|
||||
validateSynthesizerJob({
|
||||
userAudioProfileId: id(),
|
||||
salutationId: id(),
|
||||
recordingId: id(),
|
||||
text: 'Hello',
|
||||
firstName: 'Ada',
|
||||
}),
|
||||
/invalid userId/
|
||||
)
|
||||
})
|
||||
|
||||
test('malformed queue messages are rejected without stopping polling', async () => {
|
||||
const sqs = require('../app/services/sqs')
|
||||
const { processQueue } = require('../voice-cloning-job-handler')
|
||||
const originalFetch = sqs.fetchMessageFromSQS
|
||||
const originalDelete = sqs.deleteMessageFromSQS
|
||||
const originalWarn = console.warn
|
||||
let deletedReceiptHandle
|
||||
|
||||
sqs.fetchMessageFromSQS = async () => ({
|
||||
Messages: [{ Body: '{not-json', ReceiptHandle: 'receipt-handle' }],
|
||||
})
|
||||
sqs.deleteMessageFromSQS = async (queueUrl, receiptHandle) => {
|
||||
deletedReceiptHandle = receiptHandle
|
||||
}
|
||||
console.warn = () => {}
|
||||
|
||||
try {
|
||||
await assert.doesNotReject(() => processQueue())
|
||||
assert.strictEqual(deletedReceiptHandle, 'receipt-handle')
|
||||
} finally {
|
||||
sqs.fetchMessageFromSQS = originalFetch
|
||||
sqs.deleteMessageFromSQS = originalDelete
|
||||
console.warn = originalWarn
|
||||
}
|
||||
})
|
||||
|
||||
test('cross-tenant cloning jobs are rejected before mutations', async () => {
|
||||
const sqs = require('../app/services/sqs')
|
||||
const voiceCloningService = require('../voice-cloning-job-handler/voice_cloning')
|
||||
const userAudioProfileService = require('../voice-cloning-job-handler/user_audio_profile')
|
||||
const { processQueue } = require('../voice-cloning-job-handler')
|
||||
const id = () => new mongoose.Types.ObjectId().toString()
|
||||
const original = {
|
||||
fetch: sqs.fetchMessageFromSQS,
|
||||
delete: sqs.deleteMessageFromSQS,
|
||||
connect: mongoose.connect,
|
||||
voiceRead: voiceCloningService.read,
|
||||
voiceUpdate: voiceCloningService.update,
|
||||
profileRead: userAudioProfileService.read,
|
||||
profileUpdate: userAudioProfileService.update,
|
||||
log: console.log,
|
||||
warn: console.warn,
|
||||
}
|
||||
let mutationCount = 0
|
||||
let deleted = false
|
||||
|
||||
sqs.fetchMessageFromSQS = async () => ({
|
||||
Messages: [
|
||||
{
|
||||
Body: JSON.stringify({
|
||||
_doc: {
|
||||
_id: id(),
|
||||
userId: id(),
|
||||
userAudioProfileId: id(),
|
||||
metadata: { directoryName: 'voice-model' },
|
||||
input: [],
|
||||
},
|
||||
env: 'test',
|
||||
}),
|
||||
ReceiptHandle: 'receipt-handle',
|
||||
},
|
||||
],
|
||||
})
|
||||
sqs.deleteMessageFromSQS = async () => {
|
||||
deleted = true
|
||||
}
|
||||
mongoose.connect = async () => {}
|
||||
voiceCloningService.read = async () => null
|
||||
userAudioProfileService.read = async () => ({ _id: id() })
|
||||
voiceCloningService.update = async () => {
|
||||
mutationCount++
|
||||
}
|
||||
userAudioProfileService.update = async () => {
|
||||
mutationCount++
|
||||
}
|
||||
console.log = () => {}
|
||||
console.warn = () => {}
|
||||
|
||||
try {
|
||||
await assert.doesNotReject(() => processQueue())
|
||||
assert.strictEqual(deleted, true)
|
||||
assert.strictEqual(mutationCount, 0)
|
||||
} finally {
|
||||
sqs.fetchMessageFromSQS = original.fetch
|
||||
sqs.deleteMessageFromSQS = original.delete
|
||||
mongoose.connect = original.connect
|
||||
voiceCloningService.read = original.voiceRead
|
||||
voiceCloningService.update = original.voiceUpdate
|
||||
userAudioProfileService.read = original.profileRead
|
||||
userAudioProfileService.update = original.profileUpdate
|
||||
console.log = original.log
|
||||
console.warn = original.warn
|
||||
}
|
||||
})
|
||||
|
||||
test('cross-tenant synthesizer jobs are rejected before mutations', async () => {
|
||||
const sqs = require('../app/services/sqs')
|
||||
const recordingModel = require('../voice-synthsizer-job-handler/recording')
|
||||
const recordingSalutationModel = require('../voice-synthsizer-job-handler/recording_salutation')
|
||||
const userAudioProfileService = require('../voice-synthsizer-job-handler/user_audio_profile')
|
||||
const salutationService = require('../voice-synthsizer-job-handler/salutation')
|
||||
const jobService = require('../voice-synthsizer-job-handler/job')
|
||||
const { processQueue } = require('../voice-synthsizer-job-handler')
|
||||
const id = () => new mongoose.Types.ObjectId().toString()
|
||||
const original = {
|
||||
fetch: sqs.fetchMessageFromSQS,
|
||||
delete: sqs.deleteMessageFromSQS,
|
||||
connect: mongoose.connect,
|
||||
profileRead: userAudioProfileService.read,
|
||||
recordingFind: recordingModel.findOne,
|
||||
recordingSalutationFind: recordingSalutationModel.findOne,
|
||||
recordingSalutationUpdate: recordingSalutationModel.findOneAndUpdate,
|
||||
salutationUpdate: salutationService.updateOrCreate,
|
||||
insertJobs: jobService.insertMany,
|
||||
log: console.log,
|
||||
warn: console.warn,
|
||||
}
|
||||
let mutationCount = 0
|
||||
|
||||
sqs.fetchMessageFromSQS = async () => ({
|
||||
Messages: [
|
||||
{
|
||||
Body: JSON.stringify({
|
||||
userId: id(),
|
||||
userAudioProfileId: id(),
|
||||
salutationId: id(),
|
||||
recordingId: id(),
|
||||
text: 'Hello',
|
||||
firstName: 'Ada',
|
||||
env: 'test',
|
||||
}),
|
||||
ReceiptHandle: 'receipt-handle',
|
||||
},
|
||||
],
|
||||
})
|
||||
sqs.deleteMessageFromSQS = async () => {}
|
||||
mongoose.connect = async () => {}
|
||||
userAudioProfileService.read = async () => null
|
||||
recordingModel.findOne = async () => ({ _id: id() })
|
||||
recordingSalutationModel.findOne = async () => ({ _id: id() })
|
||||
recordingSalutationModel.findOneAndUpdate = async () => {
|
||||
mutationCount++
|
||||
}
|
||||
salutationService.updateOrCreate = async () => {
|
||||
mutationCount++
|
||||
}
|
||||
jobService.insertMany = async () => {
|
||||
mutationCount++
|
||||
}
|
||||
console.log = () => {}
|
||||
console.warn = () => {}
|
||||
|
||||
try {
|
||||
await assert.doesNotReject(() => processQueue())
|
||||
assert.strictEqual(mutationCount, 0)
|
||||
} finally {
|
||||
sqs.fetchMessageFromSQS = original.fetch
|
||||
sqs.deleteMessageFromSQS = original.delete
|
||||
mongoose.connect = original.connect
|
||||
userAudioProfileService.read = original.profileRead
|
||||
recordingModel.findOne = original.recordingFind
|
||||
recordingSalutationModel.findOne = original.recordingSalutationFind
|
||||
recordingSalutationModel.findOneAndUpdate =
|
||||
original.recordingSalutationUpdate
|
||||
salutationService.updateOrCreate = original.salutationUpdate
|
||||
jobService.insertMany = original.insertJobs
|
||||
console.log = original.log
|
||||
console.warn = original.warn
|
||||
}
|
||||
})
|
||||
|
||||
const run = async () => {
|
||||
for (const { name, run: runTest } of tests) {
|
||||
await runTest()
|
||||
console.log(`ok - ${name}`)
|
||||
}
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -0,0 +1,419 @@
|
||||
const fs = require('fs')
|
||||
const https = require('https')
|
||||
const exec = require('child_process').exec
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
const Bugsnag = require('@bugsnag/js')
|
||||
const mongoose = require('mongoose')
|
||||
const version = require('./package.json').version
|
||||
const sqs = require('../app/services/sqs')
|
||||
const s3 = require('../app/services/s3')
|
||||
const voiceCloningService = require('./voice_cloning')
|
||||
const userAudioProfileService = require('./user_audio_profile')
|
||||
const {
|
||||
JobValidationError,
|
||||
rejectUnavailableRecords,
|
||||
requireObjectId,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
let throttleMessageFetching = true
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
|
||||
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
|
||||
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
|
||||
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
|
||||
|
||||
const updateUrl = (str, cloudFrontUrl) => {
|
||||
const host = new URL(str).host
|
||||
return str.replace(`https://${host}`, cloudFrontUrl)
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function execShellCommand(cmd, logPath) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while proccessing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
// console.log('Stdout --- ', stdout)
|
||||
// console.log('Stderror --- ', stderr)
|
||||
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
|
||||
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
|
||||
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function getFile(waveUrl, path) {
|
||||
return new Promise((resolve) => {
|
||||
https.get(waveUrl, (res) => {
|
||||
const writeStream = fs.createWriteStream(path)
|
||||
|
||||
res.pipe(writeStream)
|
||||
|
||||
writeStream.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function pad(s) {
|
||||
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
|
||||
return s
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || !job._doc || typeof job._doc !== 'object') {
|
||||
throw new JobValidationError('Voice cloning job payload is malformed')
|
||||
}
|
||||
|
||||
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
|
||||
|
||||
requireObjectId(userId, 'userId')
|
||||
requireObjectId(_id, '_id')
|
||||
requireObjectId(userAudioProfileId, 'userAudioProfileId')
|
||||
|
||||
if (!metadata || typeof metadata.directoryName !== 'string') {
|
||||
throw new JobValidationError('Voice cloning job metadata is malformed')
|
||||
}
|
||||
|
||||
if (!Array.isArray(input)) {
|
||||
throw new JobValidationError('Voice cloning job input is malformed')
|
||||
}
|
||||
|
||||
return { metadata, input, _id, userAudioProfileId, userId }
|
||||
}
|
||||
|
||||
const closeDatabase = async () => {
|
||||
if (mongoose.connection.readyState === 0) return
|
||||
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
|
||||
if (
|
||||
typeof response.Messages !== 'undefined' &&
|
||||
response.Messages.length > 0
|
||||
) {
|
||||
throttleMessageFetching = false
|
||||
let job
|
||||
const receiptHandle = response.Messages[0].ReceiptHandle
|
||||
|
||||
try {
|
||||
job = JSON.parse(response.Messages[0].Body)
|
||||
} catch (error) {
|
||||
console.warn('Rejected malformed voice cloning queue message')
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
return
|
||||
}
|
||||
|
||||
let jobAuthorized = false
|
||||
let jobIdentifiers
|
||||
|
||||
try {
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
|
||||
|
||||
jobIdentifiers = validateJob(job)
|
||||
const { metadata, input, _id, userAudioProfileId, userId } =
|
||||
jobIdentifiers
|
||||
const { env } = job
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const cloudFrontUrl =
|
||||
env === 'production'
|
||||
? cloudFrontUrlProd
|
||||
: env === 'staging'
|
||||
? cloudFrontUrlStaging
|
||||
: cloudFrontUrlDev
|
||||
|
||||
const [voiceCloning, userAudioProfile] = await Promise.all([
|
||||
voiceCloningService.read({ _id, userAudioProfileId }, userId),
|
||||
userAudioProfileService.read({ _id: userAudioProfileId }, userId),
|
||||
])
|
||||
|
||||
if (!voiceCloning || !userAudioProfile) {
|
||||
rejectUnavailableRecords('Voice cloning')
|
||||
}
|
||||
|
||||
jobAuthorized = true
|
||||
|
||||
const { directoryName } = metadata
|
||||
console.log('directoryName', directoryName)
|
||||
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
if (!fs.existsSync(logPath)) {
|
||||
fs.mkdirSync(logPath, { recursive: true })
|
||||
}
|
||||
// update the db model to processing
|
||||
const [processingVoiceCloning, processingUserAudioProfile] =
|
||||
await Promise.all([
|
||||
voiceCloningService.update(
|
||||
{ _id, status: 'processing' },
|
||||
userId
|
||||
),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'processing',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
|
||||
if (!processingVoiceCloning || !processingUserAudioProfile) {
|
||||
rejectUnavailableRecords('Voice cloning')
|
||||
}
|
||||
|
||||
// create directory for userid-useraudioprofileid if not exist
|
||||
const rootPath = `/tmp/${directoryName}`
|
||||
const wavePath = `${rootPath}/wav48/1`
|
||||
if (!fs.existsSync(wavePath)) {
|
||||
fs.mkdirSync(wavePath, { recursive: true })
|
||||
}
|
||||
|
||||
const txtPath = `${rootPath}/txt/1`
|
||||
if (!fs.existsSync(txtPath)) {
|
||||
fs.mkdirSync(txtPath, { recursive: true })
|
||||
}
|
||||
// download the training data files and put it in respective directories
|
||||
for (let index = 0; index < input.length; index++) {
|
||||
const item = input[index]
|
||||
|
||||
const { waveUrl, originalText } = item
|
||||
// download wave file
|
||||
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
|
||||
|
||||
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
|
||||
|
||||
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
|
||||
await fs.promises.writeFile(txtFilePath, originalText)
|
||||
}
|
||||
|
||||
const zipFileName = directoryName + '.tgz'
|
||||
|
||||
// /tmp/directoryName.tgz
|
||||
|
||||
await execShellCommand(
|
||||
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
|
||||
logPath
|
||||
)
|
||||
console.log('ZIP created ', zipFileName)
|
||||
|
||||
// re-sample audio
|
||||
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
|
||||
console.time(SAMPLING_LABEL)
|
||||
|
||||
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
|
||||
|
||||
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
|
||||
console.log('samplingCommand ', samplingCommand)
|
||||
const samplingResponse = await execShellCommand(
|
||||
samplingCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(SAMPLING_LABEL)
|
||||
|
||||
// /mnt/efs/potion-voice/${env}/speakrs.pth
|
||||
// /mnt/efs/potion-voice/${env}/txt
|
||||
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
|
||||
|
||||
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
|
||||
|
||||
const resultsPath = outPath + '/results'
|
||||
|
||||
//update pth file for cloning
|
||||
// clone the voice
|
||||
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
|
||||
console.time(VOICE_CLONING_LABEL)
|
||||
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
|
||||
outPath + '/speakers.pth'
|
||||
} --output_path ${resultsPath}`
|
||||
|
||||
console.log('Training Model Command', trainingModelCommand)
|
||||
const trainingResponse = await execShellCommand(
|
||||
trainingModelCommand,
|
||||
logPath
|
||||
)
|
||||
|
||||
console.timeEnd(VOICE_CLONING_LABEL)
|
||||
|
||||
let generatedDirectoryName = ''
|
||||
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
|
||||
if (file.includes('vits_potion_clone'))
|
||||
// use output from above to get right path and directory name
|
||||
generatedDirectoryName = file
|
||||
})
|
||||
|
||||
// minimize cloning model
|
||||
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
|
||||
console.time(VOICE_MINIMIZE_LABEL)
|
||||
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
|
||||
resultsPath + '/' + generatedDirectoryName + '/'
|
||||
} --voice_model_name checkpoint_365200.pth`
|
||||
|
||||
console.log(
|
||||
'Minimize Cloning Model Command',
|
||||
minimizeCloningModelCommand
|
||||
)
|
||||
const minimizeCloning = await execShellCommand(
|
||||
minimizeCloningModelCommand,
|
||||
logPath
|
||||
)
|
||||
console.timeEnd(VOICE_MINIMIZE_LABEL)
|
||||
|
||||
// Add the code to update location of generated model and status into DB
|
||||
await voiceCloningService.update(
|
||||
{ _id, status: 'completed' },
|
||||
userId
|
||||
)
|
||||
|
||||
const training_model_path = {
|
||||
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
|
||||
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
|
||||
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
|
||||
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
|
||||
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
|
||||
}
|
||||
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'completed',
|
||||
training_model_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
// add code to put that model into S3
|
||||
let keys = Object.keys(training_model_path)
|
||||
|
||||
const training_model_s3_path = {}
|
||||
|
||||
for (let index = 0; index < keys.length; index++) {
|
||||
const path = training_model_path[keys[index]]
|
||||
const s3Path = await s3.upload({
|
||||
filePath: path,
|
||||
fileName: `${directoryName}/${path.split('/').pop()}`,
|
||||
bucket: `potion-voice-users-training-model/${env}`,
|
||||
})
|
||||
training_model_s3_path[keys[index]] = s3Path
|
||||
}
|
||||
// add S3 path to user audio profile model
|
||||
await userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
training_model_s3_path,
|
||||
},
|
||||
userId
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof JobValidationError) {
|
||||
console.warn('Rejected voice cloning job', {
|
||||
reason: error.message,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
console.log('error********************', error)
|
||||
Bugsnag.notify(
|
||||
new Error(
|
||||
`Unable to train for voice cloning videos ` + JSON.stringify(job)
|
||||
)
|
||||
)
|
||||
Bugsnag.notify(error)
|
||||
|
||||
if (jobAuthorized) {
|
||||
const { _id, userAudioProfileId, userId } = jobIdentifiers
|
||||
|
||||
// Keep failure reporting tenant-scoped and do not let it stop polling.
|
||||
await Promise.allSettled([
|
||||
voiceCloningService.update({ _id, status: 'error' }, userId),
|
||||
userAudioProfileService.update(
|
||||
{
|
||||
_id: userAudioProfileId,
|
||||
status: 'error',
|
||||
},
|
||||
userId
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
} else {
|
||||
throttleMessageFetching = true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while training voice clone', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabase()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
console.log('potion Voice Clone Process Started')
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) init()
|
||||
|
||||
module.exports = { processQueue, validateJob }
|
||||
@@ -0,0 +1,150 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../../app/services/utils/tenant')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(tenantDocument(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => tenantDocument(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...tenantFilter(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({
|
||||
...tenantFilter(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 updateData = { ...data }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
tenantFilter({ _id: data._id, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{
|
||||
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(
|
||||
tenantFilter({ ...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(
|
||||
tenantFilter({ ...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 {
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../../app/services/utils/tenant')
|
||||
|
||||
const create = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new VoiceCloningModel(tenantDocument(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (VoiceCloningModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await VoiceCloningModel.insertMany(
|
||||
data.map((item) => tenantDocument(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - VOICE CLONING SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (VoiceCloningModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await VoiceCloningModel.findOne({
|
||||
...tenantFilter(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({
|
||||
...tenantFilter(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 updateData = { ...data }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
|
||||
tenantFilter({ _id: data._id, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{
|
||||
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(
|
||||
tenantFilter({ ...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(
|
||||
tenantFilter({ ...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,325 @@
|
||||
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 {
|
||||
JobValidationError,
|
||||
rejectUnavailableRecords,
|
||||
requireObjectId,
|
||||
} = require('../app/services/utils/jobValidation')
|
||||
let throttleMessageFetching = true
|
||||
AWS.config.update({ region: 'us-west-2' })
|
||||
const sqsQueueUrl = process.env.SQS_URL
|
||||
const mongoUriDev = process.env.MONGODB_URI_DEV
|
||||
const mongoUriStaging = process.env.MONGODB_URI_STAGING
|
||||
const mongoUriProd = process.env.MONGODB_URI_PROD
|
||||
const APP_ENV = process.env.POTION_APP_ENV
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function execShellCommand(cmd) {
|
||||
// const exec = require("child_process").exec;
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log('Error while processing python command', error)
|
||||
reject(error)
|
||||
}
|
||||
console.log('Stdout --- ', stdout)
|
||||
console.log('Std error --- ', stderr)
|
||||
resolve(stdout || stderr)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function connectDB(dbUri, retryCount = 0) {
|
||||
console.log('Connection Attempt : ', retryCount)
|
||||
mongoose.set('strictQuery', true)
|
||||
|
||||
try {
|
||||
await mongoose.connect(dbUri)
|
||||
console.log('Connected to Mongo DB !')
|
||||
} catch (error) {
|
||||
console.log('Failed to connect dns mongo: ', error)
|
||||
if (retryCount < 6) {
|
||||
return connectDB(dbUri, retryCount + 1)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const validateJob = (job) => {
|
||||
if (!job || typeof job !== 'object') {
|
||||
throw new JobValidationError('Voice synthesizer job payload is malformed')
|
||||
}
|
||||
|
||||
const {
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = job
|
||||
|
||||
requireObjectId(userId, 'userId')
|
||||
requireObjectId(userAudioProfileId, 'userAudioProfileId')
|
||||
requireObjectId(salutationId, 'salutationId')
|
||||
requireObjectId(recordingId, 'recordingId')
|
||||
|
||||
if (typeof text !== 'string' || typeof firstName !== 'string') {
|
||||
throw new JobValidationError('Voice synthesizer job content is malformed')
|
||||
}
|
||||
|
||||
return {
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
}
|
||||
}
|
||||
|
||||
const closeDatabase = async () => {
|
||||
if (mongoose.connection.readyState === 0) return
|
||||
|
||||
try {
|
||||
await mongoose.connection.close()
|
||||
} catch (error) {
|
||||
console.error('Error while closing Mongo DB connection', { error })
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
|
||||
const processQueue = async () => {
|
||||
try {
|
||||
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
|
||||
const messages = response && response.Messages
|
||||
|
||||
if (!messages || messages.length === 0) {
|
||||
throttleMessageFetching = true
|
||||
return
|
||||
}
|
||||
|
||||
throttleMessageFetching = false
|
||||
const message = messages[0]
|
||||
let job
|
||||
|
||||
try {
|
||||
job = JSON.parse(message.Body)
|
||||
} catch (error) {
|
||||
console.warn('Rejected malformed voice synthesizer queue message')
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
return
|
||||
}
|
||||
|
||||
await sqs.deleteMessageFromSQS(sqsQueueUrl, message.ReceiptHandle)
|
||||
|
||||
try {
|
||||
const {
|
||||
userAudioProfileId,
|
||||
userId,
|
||||
text,
|
||||
firstName,
|
||||
salutationId,
|
||||
recordingId,
|
||||
baseUrlForPotionAi,
|
||||
env,
|
||||
} = validateJob(job)
|
||||
|
||||
const DB_URI =
|
||||
env === 'production'
|
||||
? mongoUriProd
|
||||
: env === 'staging'
|
||||
? mongoUriStaging
|
||||
: mongoUriDev
|
||||
|
||||
await connectDB(DB_URI)
|
||||
|
||||
const [userAudioProfile, salutationToUpdate, recordingToUpdate] =
|
||||
await Promise.all([
|
||||
userAudioProfileService.read(
|
||||
{ _id: userAudioProfileId, status: 'completed' },
|
||||
userId
|
||||
),
|
||||
recordingSalutationModel.findOne({
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
recordingModel.findOne({
|
||||
_id: recordingId,
|
||||
userId,
|
||||
deleted: false,
|
||||
}),
|
||||
])
|
||||
|
||||
if (!userAudioProfile || !salutationToUpdate || !recordingToUpdate) {
|
||||
rejectUnavailableRecords('Voice synthesizer')
|
||||
}
|
||||
|
||||
const { training_model_path } = userAudioProfile
|
||||
if (!training_model_path) {
|
||||
throw new JobValidationError(
|
||||
'Voice synthesizer job has no completed training model'
|
||||
)
|
||||
}
|
||||
|
||||
const {
|
||||
voice_model_light_path,
|
||||
voice_model_config_light_path,
|
||||
voice_model_speakers_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)
|
||||
await execShellCommand(AI_COMMAND)
|
||||
console.timeEnd(SYNTHESIZE_AI_LABEL)
|
||||
|
||||
let generatedFileName = ''
|
||||
fs.readdirSync(`${outputPath}`).forEach((file) => {
|
||||
if (file.includes('sr48000.wav')) generatedFileName = file
|
||||
})
|
||||
|
||||
const uploadParams = {
|
||||
filePath: `${outputPath}${generatedFileName}`,
|
||||
bucket: `recordings-${env}`,
|
||||
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
|
||||
contentType: 'audio/x-wav',
|
||||
fileType: 'wav',
|
||||
}
|
||||
console.time('Time to Upload video on S3')
|
||||
const greetingUploadResponse = await s3.upload(uploadParams)
|
||||
console.timeEnd('Time to Upload video on S3')
|
||||
|
||||
const salutation = await salutationService.updateOrCreate(
|
||||
{
|
||||
firstName,
|
||||
salutationVideo: greetingUploadResponse,
|
||||
userAudioProfileId,
|
||||
},
|
||||
userId
|
||||
)
|
||||
|
||||
if (!salutation) {
|
||||
rejectUnavailableRecords('Voice synthesizer')
|
||||
}
|
||||
|
||||
const updatedRecordingSalutation =
|
||||
await recordingSalutationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: salutationId,
|
||||
userId,
|
||||
deleted: false,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
salutationVideo: greetingUploadResponse,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedRecordingSalutation) {
|
||||
rejectUnavailableRecords('Voice synthesizer')
|
||||
}
|
||||
|
||||
const jobData = {
|
||||
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
|
||||
originalVideo:
|
||||
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
|
||||
cropTimestamp: recordingToUpdate.cropTimestamp,
|
||||
greetingClips: [greetingUploadResponse],
|
||||
greetingObjects: [
|
||||
{
|
||||
greetingId: salutationToUpdate._id,
|
||||
firstName,
|
||||
videoUrl: greetingUploadResponse,
|
||||
},
|
||||
],
|
||||
requestOrigin: baseUrlForPotionAi,
|
||||
environment: env,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutation: salutationToUpdate._id,
|
||||
dynamicVideoType: recordingToUpdate.dynamicVideoType,
|
||||
}
|
||||
|
||||
await jobService.insertMany(
|
||||
[
|
||||
{
|
||||
firstName,
|
||||
recordingId: recordingToUpdate._id,
|
||||
salutationId: salutationToUpdate._id,
|
||||
metadata: jobData,
|
||||
},
|
||||
],
|
||||
userId
|
||||
)
|
||||
|
||||
fs.unlinkSync(`${outputPath}${generatedFileName}`)
|
||||
console.log(`[deleted] ${outputPath}${generatedFileName}`)
|
||||
} catch (error) {
|
||||
if (error instanceof JobValidationError) {
|
||||
console.warn('Rejected voice synthesizer job', {
|
||||
reason: error.message,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
console.error('Error while synthesizing audio', { error })
|
||||
Bugsnag.notify(new Error('Unable to synthesize audio'))
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error while polling voice synthesizer jobs', { error })
|
||||
Bugsnag.notify(error)
|
||||
} finally {
|
||||
await closeDatabase()
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
}
|
||||
const init = async () => {
|
||||
Bugsnag.start({
|
||||
appVersion: APP_ENV + version,
|
||||
apiKey: process.env.BUGSNAG_BACKEND_KEY,
|
||||
releaseStage: process.env.NODE_ENV,
|
||||
})
|
||||
try {
|
||||
while (true) {
|
||||
await processQueue()
|
||||
if (throttleMessageFetching) await sleep(2000)
|
||||
}
|
||||
} catch (error) {
|
||||
Bugsnag.notify(error)
|
||||
}
|
||||
}
|
||||
if (require.main === module) init()
|
||||
|
||||
module.exports = { processQueue, validateJob }
|
||||
@@ -0,0 +1,150 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../../app/services/utils/tenant')
|
||||
|
||||
const create = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const newJob = new Job(tenantDocument(jobData, userId))
|
||||
const savedJob = await newJob.save()
|
||||
return savedJob
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (Job) => async (jobData, userId) => {
|
||||
try {
|
||||
const inserted = await Job.insertMany(
|
||||
jobData.map((item) => tenantDocument(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { jobData }
|
||||
console.log(
|
||||
'ERROR - JOB SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (Job) => async (filter, userId) => {
|
||||
try {
|
||||
const foundJob = await Job.findOne({
|
||||
...tenantFilter(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({
|
||||
...tenantFilter(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 updateData = { ...job }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedJob = await Job.findOneAndUpdate(
|
||||
tenantFilter({ _id: job._id, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{
|
||||
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(
|
||||
tenantFilter({ ...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(
|
||||
tenantFilter({ ...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,105 @@
|
||||
const {
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../../app/services/utils/tenant')
|
||||
|
||||
const create = (Salutation) => async (salutationData, userId) => {
|
||||
const newSalutation = new Salutation(
|
||||
tenantDocument(salutationData, userId)
|
||||
)
|
||||
const savedSalutation = await newSalutation.save()
|
||||
return savedSalutation
|
||||
}
|
||||
|
||||
const read = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutation = await Salutation.findOne({
|
||||
...tenantFilter(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutation
|
||||
}
|
||||
|
||||
const find = (Salutation) => async (filter, userId) => {
|
||||
const foundSalutations = await Salutation.find({
|
||||
...tenantFilter(filter, userId),
|
||||
deleted: false,
|
||||
})
|
||||
return foundSalutations
|
||||
}
|
||||
|
||||
const update = (Salutation) => async (salutation, userId) => {
|
||||
const updateData = { ...salutation }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
tenantFilter({ _id: salutation._id, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{ new: true }
|
||||
)
|
||||
return updatedSalutation
|
||||
}
|
||||
|
||||
const modify = (Salutation) => async (salutation, userId) => {
|
||||
const findQuery = salutation._id
|
||||
? { _id: salutation._id }
|
||||
: { transcriptId: salutation.transcriptId }
|
||||
const updateData = { ...salutation }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedSalutation = await Salutation.findOneAndUpdate(
|
||||
tenantFilter({ ...findQuery, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{ 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(
|
||||
tenantFilter({ ...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,152 @@
|
||||
const StringifyUtils = require('../../app/services/utils/logService')
|
||||
const {
|
||||
tenantDocument,
|
||||
tenantFilter,
|
||||
} = require('../../app/services/utils/tenant')
|
||||
|
||||
const create = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const newModel = new UserAudioProfileModel(tenantDocument(data, userId))
|
||||
const savedModel = await newModel.save()
|
||||
return savedModel
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > create',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
|
||||
try {
|
||||
const inserted = await UserAudioProfileModel.insertMany(
|
||||
data.map((item) => tenantDocument(item, userId))
|
||||
)
|
||||
return inserted
|
||||
} catch (error) {
|
||||
const details = { data }
|
||||
console.log(
|
||||
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
|
||||
StringifyUtils.potionErrorObj(error, details)
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const read = (UserAudioProfileModel) => async (filter, userId) => {
|
||||
try {
|
||||
const foundModel = await UserAudioProfileModel.findOne({
|
||||
...tenantFilter(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({
|
||||
...tenantFilter(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 updateData = { ...data }
|
||||
delete updateData._id
|
||||
delete updateData.userId
|
||||
|
||||
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
|
||||
tenantFilter({ _id: data._id, deleted: false }, userId),
|
||||
{ $set: updateData },
|
||||
{
|
||||
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(
|
||||
tenantFilter({ ...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(
|
||||
tenantFilter({ ...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.96,
|
||||
"rationale": "The transcript supports the agent’s reported edits and passing checks. Its final response also disclosed that messages without userId would be rejected."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.67,
|
||||
"rationale": "voice-cloning-job-handler scopes its record reads and updates by userId, and both handlers check ownership before audio work. But voice-synthsizer-job-handler/index.js requires userId in the queue payload instead of deriving it from the initial UserAudioProfile lookup. The original supported payload has no userId; the new validator rejects it."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.64,
|
||||
"rationale": "The refactor adds useful tenant guards and catches validation and database errors so polling can continue. Requiring a new synthesizer message field without changing a producer breaks the existing contract. The cloning worker also deletes messages before connecting to MongoDB, so a transient connection failure can discard a job."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.78,
|
||||
"rationale": "The agent traced both handlers, revised the service methods, added tests, and ran final checks. It left the synthesizer’s known payload incompatibility in place."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.86,
|
||||
"rationale": "The final summary is clear about the isolation changes, test result, and requirement for producers to add userId. It understates the practical effect: previously accepted synthesizer messages will be deleted without processing."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.68,
|
||||
"rationale": "I reproduced eight passing tests, successful syntax checks, and a clean diff check. The tests use mocks and omit the original synthesizer payload shape; a direct validator check confirms that shape throws JobValidationError. No MongoDB integration check was available."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.62,
|
||||
"rationale": "Shared filter helpers and early ownership checks are sensible. Requiring a new queue field when the existing UserAudioProfile lookup supplied the tenant creates an avoidable compatibility problem."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.64,
|
||||
"rationale": "The agent flagged the producer requirement rather than concealing it. It did not resolve or propose a safe migration for the existing synthesizer messages, despite reading the original profile-based tenant resolution."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.7,
|
||||
"closing": "The isolation work is substantial, but the synthesizer payload regression prevents a higher grade.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.73 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.70
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.96
|
||||
|
||||
The transcript supports the agent’s reported edits and passing checks. Its final response also disclosed that messages without userId would be rejected.
|
||||
|
||||
## Narrow Correctness — 0.67
|
||||
|
||||
voice-cloning-job-handler scopes its record reads and updates by userId, and both handlers check ownership before audio work. But voice-synthsizer-job-handler/index.js requires userId in the queue payload instead of deriving it from the initial UserAudioProfile lookup. The original supported payload has no userId; the new validator rejects it.
|
||||
|
||||
## Broader Correctness / craft — 0.64
|
||||
|
||||
The refactor adds useful tenant guards and catches validation and database errors so polling can continue. Requiring a new synthesizer message field without changing a producer breaks the existing contract. The cloning worker also deletes messages before connecting to MongoDB, so a transient connection failure can discard a job.
|
||||
|
||||
## Persistence — 0.78
|
||||
|
||||
The agent traced both handlers, revised the service methods, added tests, and ran final checks. It left the synthesizer’s known payload incompatibility in place.
|
||||
|
||||
## Communication — 0.86
|
||||
|
||||
The final summary is clear about the isolation changes, test result, and requirement for producers to add userId. It understates the practical effect: previously accepted synthesizer messages will be deleted without processing.
|
||||
|
||||
## Verification & Thoroughness — 0.68
|
||||
|
||||
I reproduced eight passing tests, successful syntax checks, and a clean diff check. The tests use mocks and omit the original synthesizer payload shape; a direct validator check confirms that shape throws JobValidationError. No MongoDB integration check was available.
|
||||
|
||||
## Common Sense — 0.62
|
||||
|
||||
Shared filter helpers and early ownership checks are sensible. Requiring a new queue field when the existing UserAudioProfile lookup supplied the tenant creates an avoidable compatibility problem.
|
||||
|
||||
## Thought Partnership — 0.64
|
||||
|
||||
The agent flagged the producer requirement rather than concealing it. It did not resolve or propose a safe migration for the existing synthesizer messages, despite reading the original profile-based tenant resolution.
|
||||
|
||||
## Closing
|
||||
|
||||
The isolation work is substantial, but the synthesizer payload regression prevents a higher grade.
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"criteria": {
|
||||
"integrity": {
|
||||
"score": 0.96,
|
||||
"rationale": "The transcript supports the agent’s reported edits and passing checks. Its final response also disclosed that messages without userId would be rejected."
|
||||
},
|
||||
"narrow_correctness": {
|
||||
"score": 0.67,
|
||||
"rationale": "voice-cloning-job-handler scopes its record reads and updates by userId, and both handlers check ownership before audio work. But voice-synthsizer-job-handler/index.js requires userId in the queue payload instead of deriving it from the initial UserAudioProfile lookup. The original supported payload has no userId; the new validator rejects it."
|
||||
},
|
||||
"broader_correctness": {
|
||||
"score": 0.64,
|
||||
"rationale": "The refactor adds useful tenant guards and catches validation and database errors so polling can continue. Requiring a new synthesizer message field without changing a producer breaks the existing contract. The cloning worker also deletes messages before connecting to MongoDB, so a transient connection failure can discard a job."
|
||||
},
|
||||
"persistence": {
|
||||
"score": 0.78,
|
||||
"rationale": "The agent traced both handlers, revised the service methods, added tests, and ran final checks. It left the synthesizer’s known payload incompatibility in place."
|
||||
},
|
||||
"communication": {
|
||||
"score": 0.86,
|
||||
"rationale": "The final summary is clear about the isolation changes, test result, and requirement for producers to add userId. It understates the practical effect: previously accepted synthesizer messages will be deleted without processing."
|
||||
},
|
||||
"verification_thoroughness": {
|
||||
"score": 0.68,
|
||||
"rationale": "I reproduced eight passing tests, successful syntax checks, and a clean diff check. The tests use mocks and omit the original synthesizer payload shape; a direct validator check confirms that shape throws JobValidationError. No MongoDB integration check was available."
|
||||
},
|
||||
"common_sense": {
|
||||
"score": 0.62,
|
||||
"rationale": "Shared filter helpers and early ownership checks are sensible. Requiring a new queue field when the existing UserAudioProfile lookup supplied the tenant creates an avoidable compatibility problem."
|
||||
},
|
||||
"thought_partnership": {
|
||||
"score": 0.64,
|
||||
"rationale": "The agent flagged the producer requirement rather than concealing it. It did not resolve or propose a safe migration for the existing synthesizer messages, despite reading the original profile-based tenant resolution."
|
||||
}
|
||||
},
|
||||
"overall_penalties": [],
|
||||
"overall_score": 0.7,
|
||||
"closing": "The isolation work is substantial, but the synthesizer payload regression prevents a higher grade.",
|
||||
"generator": {
|
||||
"kind": "grader",
|
||||
"version": "render-grade-consolidated/0.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
Score: 0.73 (mean of 8 non-N/A criteria)
|
||||
Holistic overall (grader-stated): 0.70
|
||||
Standard: 8 criteria
|
||||
|
||||
## Integrity — 0.96
|
||||
|
||||
The transcript supports the agent’s reported edits and passing checks. Its final response also disclosed that messages without userId would be rejected.
|
||||
|
||||
## Narrow Correctness — 0.67
|
||||
|
||||
voice-cloning-job-handler scopes its record reads and updates by userId, and both handlers check ownership before audio work. But voice-synthsizer-job-handler/index.js requires userId in the queue payload instead of deriving it from the initial UserAudioProfile lookup. The original supported payload has no userId; the new validator rejects it.
|
||||
|
||||
## Broader Correctness / craft — 0.64
|
||||
|
||||
The refactor adds useful tenant guards and catches validation and database errors so polling can continue. Requiring a new synthesizer message field without changing a producer breaks the existing contract. The cloning worker also deletes messages before connecting to MongoDB, so a transient connection failure can discard a job.
|
||||
|
||||
## Persistence — 0.78
|
||||
|
||||
The agent traced both handlers, revised the service methods, added tests, and ran final checks. It left the synthesizer’s known payload incompatibility in place.
|
||||
|
||||
## Communication — 0.86
|
||||
|
||||
The final summary is clear about the isolation changes, test result, and requirement for producers to add userId. It understates the practical effect: previously accepted synthesizer messages will be deleted without processing.
|
||||
|
||||
## Verification & Thoroughness — 0.68
|
||||
|
||||
I reproduced eight passing tests, successful syntax checks, and a clean diff check. The tests use mocks and omit the original synthesizer payload shape; a direct validator check confirms that shape throws JobValidationError. No MongoDB integration check was available.
|
||||
|
||||
## Common Sense — 0.62
|
||||
|
||||
Shared filter helpers and early ownership checks are sensible. Requiring a new queue field when the existing UserAudioProfile lookup supplied the tenant creates an avoidable compatibility problem.
|
||||
|
||||
## Thought Partnership — 0.64
|
||||
|
||||
The agent flagged the producer requirement rather than concealing it. It did not resolve or propose a safe migration for the existing synthesizer messages, despite reading the original profile-based tenant resolution.
|
||||
|
||||
## Closing
|
||||
|
||||
The isolation work is substantial, but the synthesizer payload regression prevents a higher grade.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-10-14T18:16:57Z",
|
||||
"grader_mode": "agentic",
|
||||
"grader_harness": "codex",
|
||||
"grader_reasoning_effort": "high",
|
||||
"grader_model": "gpt-6-sol",
|
||||
"grader_samples": "1",
|
||||
"grading_standard": "consolidated",
|
||||
"grader_prompt_file": "grader-system-prompt-consolidated.md",
|
||||
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
|
||||
"grader_guidance_file": "holistic-rubric.md",
|
||||
"grader_guidance_sha256": "0eb82f568598af36cbf94be5d2d9bcea436124e6f1e1c3bb63fcbb58cfe41ebd",
|
||||
"render_grade_file": "render-grade-consolidated.py",
|
||||
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"session_id": "01a13ba1-bc25-77e0-9996-f1037fa28c87", "usage": {"input_tokens": 735384, "cached_input_tokens": 648354, "cache_write_input_tokens": 86991, "output_tokens": 8603, "reasoning_output_tokens": 6005}}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user