evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

fix: delete instance cleanup on baileys failure

Open antonio-abrantes opened this issue 7 months ago • 3 comments

📋 Description

🐛 Problem

When calling DELETE /instance/delete/{instanceName} on a corrupted instance (disconnected/bugged Baileys session), the API returns:

{
  "status": 400,
  "error": "Bad Request",
  "response": { "message": ["[object Object]"] }
}

After this error, the instance name remains permanently blocked in waInstances memory. Even after manually cleaning the database, Redis, and session files, calling POST /instance/create with the same name returns:

{
  "status": 403,
  "message": ["This name \"agent-xxx\" is already in use."]
}

The only workaround was restarting the container — not viable in production environments.


🔍 Root Cause

Two bugs working together:

1. Aborted cleanup

  • deleteInstance() stopped execution if logout() failed

2. Bad error serialization

  • Errors returned as [object Object]

✅ Fix

  • Split try/catch into isolated steps

  • Ensure cleanup always runs

  • Always remove instance from waInstances

  • Fix error serialization using:

    error?.message ?? String(error)
    

🔗 Related Issue

Closes # (leave empty if not applicable)


🧪 Type of Change

  • [x] 🐛 Bug fix (non-breaking change which fixes an issue)
  • [ ] ✨ New feature
  • [ ] 💥 Breaking change
  • [ ] 📚 Documentation update
  • [ ] 🔧 Refactoring
  • [ ] ⚡ Performance improvement
  • [ ] 🧹 Code cleanup
  • [ ] 🔒 Security fix

🧪 Testing

  • [x] Manual testing completed
  • [x] Functionality verified in development environment
  • [x] No breaking changes introduced
  • [ ] Tested with different connection types

📸 Screenshots (if applicable)

N/A


✅ Checklist

  • [x] My code follows the project's style guidelines
  • [x] I have performed a self-review of my code
  • [x] My changes generate no new warnings
  • [x] I have manually tested my changes thoroughly
  • [x] I have verified the changes work with different scenarios

📝 Additional Notes

Tested in production environment with Docker Swarm + PostgreSQL + Redis. Fix only affects failure path — no impact on healthy instances.


⚠️ Behavior Change — Contract Documentation

The endpoint now returns { status: 'SUCCESS' } even on partial failures. Logout and webhook steps were changed from "abort on error" to logger.warn. This is intentional — the cleanup is best-effort to ensure the instance name is always released from waInstances memory, even when secondary steps fail.

Clients relying on 4xx responses to detect cleanup failures will need to adjust their logic.

antonio-abrantes avatar Apr 18 '26 01:04 antonio-abrantes

Hi! As part of our PR triage, we re-ran CI on this PR and the Check Code Quality workflow is failing. Could you please:

  1. Check the latest run output (Actions tab on this PR) and address the build/lint errors
  2. Push the fix to your branch — CI will re-run automatically (no need to ping us; it's now auto-approved)
  3. Make sure the base branch is develop (already adjusted on our side)

Once CI is green I'll re-review for merge. Thanks!

DavidsonGomes avatar May 06 '26 18:05 DavidsonGomes

Boa refatoração — quebrar o try/catch monolítico em steps isolados é a forma idiomática correta de cleanup robusto, e adicionar await em cleaningUp e cleaningStoreData corrige uma race condition latente.

Bloqueadores para o merge:

  • [ ] Rebase — PR está CONFLITANDO com main
  • [ ] Rodar npm run lint -- --fix — CI falha com 85 erros prettier em monitor.service.ts (linhas 1850-2791, formatação automática)
  • [ ] Documentar mudança de contrato no PR body: o endpoint passa a retornar { status: 'SUCCESS' } mesmo em falhas parciais (logout/webhook viram logger.warn em vez de abortar). Isso é uma escolha deliberada — o cleanup é "best effort" para liberar o nome da instância — mas merece estar explícito para clientes que dependiam de 4xx.

Após os 3 itens, aprovo.

DavidsonGomes avatar May 17 '26 22:05 DavidsonGomes

Olá @antonio-abrantes, obrigado pela contribuição — o fix está correto e endereça um problema real de produção (instâncias travadas no waInstances em memória após falha de cleanup).

A PR está em estado CONFLICTING com develop. Pode fazer rebase contra develop quando puder?

git fetch upstream
git rebase upstream/develop
git push --force-with-lease

Após o rebase, mergeio. Obrigado!

DavidsonGomes avatar May 19 '26 14:05 DavidsonGomes

🟢 👍

Na develop e focado: melhora o cleanup ao deletar instância quando o Baileys falha — isola o try/catch por etapa e adiciona os await que faltavam, sem reescrever a lógica. Pode seguir.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias