docs(session-2026-05-12): audit types drift + backup procedures + DBA session report#130
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
WalkthroughPR adiciona automação de validação periódica para backups Postgres self-hosted Supabase: script ChangesBackup & Restore Automation
sequenceDiagram
participant Operator as Operador
participant Cron as Cron Host
participant BackupContainer as supabase-backup_backup
participant RestoreScript as restore-test.sh
participant Postgres as PostgreSQL
participant FS as Filesystem/Logs
Operator->>Cron: instalar cron via `install-restore-test-cron.sh`
Cron->>BackupContainer: docker exec /backups/restore-test.sh (agendado)
BackupContainer->>RestoreScript: executar script de restore
RestoreScript->>FS: localizar dump + validar .sha256
RestoreScript->>Postgres: criar DB temporária
RestoreScript->>FS: gerar e filtrar TOC (remover pg_cron)
RestoreScript->>Postgres: executar pg_restore (timeout 10m)
Postgres-->>RestoreScript: resultado restore
RestoreScript->>Postgres: consultas de validação (counts, tamanho)
RestoreScript->>FS: escrever logs e marker PASS/FAIL
🎯 3 (Moderate) | ⏱️ ~25 minutes Possivelmente relacionado:
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4ca2f68f4a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \ | ||
| --use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \ | ||
| "$LATEST" >> $LOG 2>&1 || true |
There was a problem hiding this comment.
Do not ignore pg_restore failures
In the monthly restore-test path, any nonzero pg_restore exit (timeout, corrupted dump section, missing extension/object errors) is swallowed by || true, so the script can still report RESTORE TEST PASSOU if the few count queries exceed the thresholds after a partial restore. Since this script is meant to validate disaster recovery, please fail the test and create the failure marker when pg_restore returns nonzero instead of relying only on row-count heuristics.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/backups/restore-test.sh`:
- Around line 66-68: O comando de restauração usa "|| true", o que oculta falhas
de pg_restore/timeout; remova "|| true", capture o código de saída imediatamente
após o comando (ex.: rc=$?) e passe esse rc como primeira condição no check de
sucesso usado depois (referencie o comando timeout 600 pg_restore -d $DBNAME ...
"$LATEST" >> $LOG 2>&1 e a checagem de sucesso existente), de forma que qualquer
rc != 0 (incluindo timeouts) faça o script marcar FAILED.
- Around line 39-47: The checksum flow can be interrupted by set -e if cd fails;
wrap the cd and sha256sum in a subshell used directly by the if so the exit
status is captured without aborting the script. Replace the current separate
cd/sha256sum + subsequent if [ $? -eq 0 ] check with an if that runs (cd
/backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1); then
call log "OK: SHA256 válido" else call log "ERRO: SHA256 FALHOU - backup
corrompido!", create the RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S) marker and
exit 2, keeping references to LATEST, the log function, and the
RESTORE_TEST_FAILED marker.
In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 105-107: Update the session report line that currently reads
"**STATUS: ⚠️ AINDA NÃO ABERTO**" to reflect that the PR is open by changing the
status text to something like "**STATUS: ✅ ABERTO — PR `#130` (2026-05-12)**", and
ensure the PR number "#130" and date "2026-05-12" are included next to the
status; modify the string in SESSION_REPORT.md where that exact status line
appears so the handoff reflects the current PR state.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: af3abd6e-1557-4ebd-bf72-f750719bcfc7
📒 Files selected for processing (6)
docs/backups/README.mddocs/backups/install-restore-test-cron.shdocs/backups/restore-test.shdocs/session-2026-05-12/SESSION_REPORT.mddocs/types-drift-2026-05/AUDIT_REPORT.mddocs/types-drift-2026-05/missing-tables-from-types.txt
There was a problem hiding this comment.
Pull request overview
Documentation + operational artifacts from the 2026-05-12 BPM/DBA session, including a recorded schema/types drift audit and a scripted monthly restore test procedure for the self-hosted Supabase backups.
Changes:
- Adds a drift audit report comparing
src/integrations/supabase/types.tsvs the self-hosted production DB, plus the full list of missing tables. - Adds backup/DR documentation and two operational scripts: an automated restore-test and a cron installer for monthly execution.
- Adds a consolidated session report capturing what was changed in production (state changes) vs what is versioned in this repo.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/types-drift-2026-05/missing-tables-from-types.txt | Full list of tables present in DB but missing from types.ts. |
| docs/types-drift-2026-05/AUDIT_REPORT.md | Human-readable drift summary + regeneration options. |
| docs/session-2026-05-12/SESSION_REPORT.md | Session log of production actions + repo artifacts. |
| docs/backups/restore-test.sh | Automated restore validation script intended to run monthly. |
| docs/backups/README.md | DR/restore procedure and deployment notes for the backup container. |
| docs/backups/install-restore-test-cron.sh | Host-side helper to install a monthly cron job running the restore test. |
Comments suppressed due to low confidence (3)
docs/backups/restore-test.sh:47
- Because
set -eis enabled, a failingsha256sum -cwill terminate the script immediately, so the subsequent$?check and failure logging won't run. Wrap the checksum validation directly in theif ...; thencondition (or otherwise capture the exit code without triggeringset -e) so failures are logged and handled consistently.
if [ -f "${LATEST}.sha256" ]; then
cd /backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1
if [ $? -eq 0 ]; then
log "OK: SHA256 válido"
else
log "ERRO: SHA256 FALHOU - backup corrompido!"
touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)
exit 2
fi
docs/backups/restore-test.sh:61
- The grep pattern uses
\|alternation without-E. This is not portable across grep implementations and can silently fail, causing pg_cron objects to be restored when they shouldn't. Prefergrep -E(oregrep) withpg_cron|cron\.for predictable behavior.
pg_restore -l "$LATEST" > /tmp/toc-${DBNAME}.list 2>/dev/null
grep -v 'pg_cron\|cron\.' /tmp/toc-${DBNAME}.list > /tmp/toc-${DBNAME}.filtered
docs/backups/restore-test.sh:69
pg_restoreerrors are currently ignored (... || true). This can produce a misleading PASS if enough rows restore to satisfy the thresholds while critical objects failed to restore. Capture thepg_restoreexit status and treat non-zero as failure (while still collecting counts/logs), or at least include the exit status in the pass/fail decision.
log "Iniciando pg_restore (timeout 10min)..."
timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \
--use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \
"$LATEST" >> $LOG 2>&1 || true
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| set -e | ||
|
|
||
| LOG=/backups/restore-test.log | ||
| DATE=$(date -Iseconds) | ||
|
|
||
| log() { | ||
| echo "[$DATE] $*" | tee -a "$LOG" | ||
| } | ||
|
|
||
| log "==================== RESTORE TEST INICIADO ====================" | ||
|
|
||
| # 1. Identificar backup mais recente | ||
| LATEST=$(ls -t /backups/supabase_selfhosted_*.dump 2>/dev/null | head -1) | ||
|
|
||
| if [ -z "$LATEST" ]; then | ||
| log "ERRO: nenhum backup encontrado em /backups/supabase_selfhosted_*.dump" | ||
| touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S) | ||
| exit 1 | ||
| fi |
| DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)" | ||
| log "Criando BD temporário: $DBNAME" | ||
| psql -c "DROP DATABASE IF EXISTS $DBNAME;" >/dev/null 2>&1 | ||
| psql -c "CREATE DATABASE $DBNAME;" >/dev/null 2>&1 | ||
|
|
| DATE=$(date -Iseconds) | ||
|
|
||
| log() { | ||
| echo "[$DATE] $*" | tee -a "$LOG" |
| BACKUP_CONTAINER="supabase-backup_backup" | ||
|
|
||
| # Comando a executar: roda o script dentro do container | ||
| CRON_LINE="0 4 1 * * /usr/bin/docker exec \$(docker ps -qf name=${BACKUP_CONTAINER}) /backups/restore-test.sh >> /var/log/restore-test-cron.log 2>&1" | ||
|
|
|
|
||
| # 4. Gerar TOC e filtrar pg_cron | ||
| pg_restore -l /backups/supabase_selfhosted_YYYYMMDD_HHMMSS.dump > /tmp/toc.list | ||
| grep -v 'pg_cron\|cron\.' /tmp/toc.list > /tmp/toc.filtered |
| git checkout feat/audit-types-drift-2026-05 | ||
| cd src/integrations/supabase | ||
|
|
||
| # Conectar à instância self-hosted | ||
| export SUPABASE_DB_URL="postgresql://supabase_admin:[PASSWORD]@supabase.atomicabr.com.br:5432/postgres" | ||
|
|
||
| # Gerar tipos | ||
| npx supabase gen types typescript --db-url $SUPABASE_DB_URL --schema public > types.new.ts |
| psql -c "DROP DATABASE IF EXISTS $DBNAME;" >/dev/null 2>&1 | ||
| psql -c "CREATE DATABASE $DBNAME;" >/dev/null 2>&1 |
| - **STATUS: ⚠️ AINDA NÃO ABERTO** — branch existe com 4 commits + este, mas precisa | ||
| de aprovação do operador antes de eu abrir o PR. | ||
|
|
||
| --- | ||
|
|
||
| ## 🎯 Próximos passos sugeridos para o operador (Joaquim) | ||
|
|
||
| 1. **Revisar este PR** quando for aberto e mergear para `main`. |
|
@coderabbitai review Solicitando review fresh com a config completa do Generated by Claude Code |
|
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
♻️ Duplicate comments (3)
docs/session-2026-05-12/SESSION_REPORT.md (1)
105-107:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winStatus do PR está desatualizado no relatório da sessão.
O texto diz "AINDA NÃO ABERTO", mas este PR já está aberto (
#130, 2026-05-12). Vale corrigir para evitar ruído operacional no handoff.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/session-2026-05-12/SESSION_REPORT.md` around lines 105 - 107, Summary: The session report's PR status line still reads "STATUS: ⚠️ AINDA NÃO ABERTO" but the PR (`#130`, 2026-05-12) is already open. Fix: edit the STATUS line in SESSION_REPORT.md to reflect the PR is open (e.g., "STATUS: ✅ ABERTO — PR `#130` (2026-05-12)"), remove the note about needing operator approval, and ensure the branch/commit context remains if needed; update the text that referenced operator approval so it no longer contradicts the open PR status.docs/backups/restore-test.sh (2)
39-47:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winFluxo de checksum quebrado com
set -e— script pode sair antes de logar/marcar falha.Se
cd /backupsfalhar na linha 40,set -emata o script imediatamente, nunca atingindo oif [ $? -eq 0 ](linha 41). O log de erro, marker file e exit 2 nunca executam. Use subshell comifpara capturar o exit code sem ser interrompido porset -e.Diff sugerido
if [ -f "${LATEST}.sha256" ]; then - cd /backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1 - if [ $? -eq 0 ]; then + if (cd /backups && sha256sum -c "$(basename "$LATEST").sha256" >/dev/null 2>&1); then log "OK: SHA256 válido" else log "ERRO: SHA256 FALHOU - backup corrompido!" - touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S) + touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)" exit 2 fi🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/backups/restore-test.sh` around lines 39 - 47, The current two-step change-directory plus `sha256sum` call can be interrupted by `set -e` if `cd /backups` fails, so replace the `cd /backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1` plus the separate `if [ $? -eq 0 ]` check with a single guarded if using a subshell, e.g. `if (cd /backups && sha256sum -c "$(basename ${LATEST}).sha256") >/dev/null 2>&1; then` to ensure the exit status of the combined operation is tested atomically; keep the existing `log "OK: SHA256 válido"` on success and in the else branch run `log "ERRO: SHA256 FALHOU - backup corrompido!"`, `touch /backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)` and `exit 2` so failures are always logged/marked even when `set -e` is enabled.
66-68:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCapturar falha de
pg_restoree forçarFAILED.O
|| truena linha 68 mascara falhas depg_restoreou timeout. Mesmo que a operação falhe (exit code != 0 ou timeout), o script segue adiante. Se o restore falha parcialmente mas deixa o banco com algumas tabelas/registros, o teste pode passar incorretamente baseado nas contagens de threshold.Solução: Capture o exit code real de
pg_restoree inclua-o como primeira condição no check de sucesso (linha 89). Assim, falha crítica no restore sempre resulta emFAILED.Diff sugerido
-timeout 600 pg_restore -d $DBNAME --no-owner --no-acl \ +if timeout 600 pg_restore -d "$DBNAME" --no-owner --no-acl \ --use-list=/tmp/toc-${DBNAME}.filtered --jobs=4 \ - "$LATEST" >> $LOG 2>&1 || true + "$LATEST" >> "$LOG" 2>&1; then + RESTORE_OK=1 +else + RESTORE_OK=0 +fi @@ -if [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then +if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/backups/restore-test.sh` around lines 66 - 68, Remove the unconditional "|| true" that masks pg_restore failures, capture its real exit code right after the timeout pg_restore invocation (use a variable like RESTORE_EXIT=$?), and then make the later success check include RESTORE_EXIT == 0 as the first required condition so any non-zero exit (including timeout) forces the script to mark FAILED; reference the timeout pg_restore invocation that uses "$LATEST", $DBNAME, $LOG and the later success/threshold check to add the RESTORE_EXIT check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@docs/backups/restore-test.sh`:
- Around line 39-47: The current two-step change-directory plus `sha256sum` call
can be interrupted by `set -e` if `cd /backups` fails, so replace the `cd
/backups && sha256sum -c "$(basename ${LATEST}).sha256" >/dev/null 2>&1` plus
the separate `if [ $? -eq 0 ]` check with a single guarded if using a subshell,
e.g. `if (cd /backups && sha256sum -c "$(basename ${LATEST}).sha256") >/dev/null
2>&1; then` to ensure the exit status of the combined operation is tested
atomically; keep the existing `log "OK: SHA256 válido"` on success and in the
else branch run `log "ERRO: SHA256 FALHOU - backup corrompido!"`, `touch
/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)` and `exit 2` so failures
are always logged/marked even when `set -e` is enabled.
- Around line 66-68: Remove the unconditional "|| true" that masks pg_restore
failures, capture its real exit code right after the timeout pg_restore
invocation (use a variable like RESTORE_EXIT=$?), and then make the later
success check include RESTORE_EXIT == 0 as the first required condition so any
non-zero exit (including timeout) forces the script to mark FAILED; reference
the timeout pg_restore invocation that uses "$LATEST", $DBNAME, $LOG and the
later success/threshold check to add the RESTORE_EXIT check.
In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 105-107: Summary: The session report's PR status line still reads
"STATUS: ⚠️ AINDA NÃO ABERTO" but the PR (`#130`, 2026-05-12) is already open.
Fix: edit the STATUS line in SESSION_REPORT.md to reflect the PR is open (e.g.,
"STATUS: ✅ ABERTO — PR `#130` (2026-05-12)"), remove the note about needing
operator approval, and ensure the branch/commit context remains if needed;
update the text that referenced operator approval so it no longer contradicts
the open PR status.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1d210281-a90f-48d9-bd0d-48f16197af85
📒 Files selected for processing (6)
docs/backups/README.mddocs/backups/install-restore-test-cron.shdocs/backups/restore-test.shdocs/session-2026-05-12/SESSION_REPORT.mddocs/types-drift-2026-05/AUDIT_REPORT.mddocs/types-drift-2026-05/missing-tables-from-types.txt
restore-test.sh (5 fixes em 1): - pg_restore: captura exit code real e usa como 1ª condição obrigatória no check de sucesso (antes `|| true` mascarava timeouts/falhas). - SHA256: subshell + if direto para não ser interrompido por `set -e` se `cd` falhar antes do bloco de erro. - `ls` com fallback `|| true` para permitir o check `[ -z $LATEST ]`. - DBNAME quoted em SQL + DROP DATABASE WITH (FORCE) para evitar conexões pendentes no BD temporário derrubarem o cron. - log() agora avalia `date -Iseconds` por linha (era fixo no startup). - grep -Ev '(pg_cron|cron\\.)' portável (sem alternação não-POSIX). install-restore-test-cron.sh: - pré-flight valida que o container está rodando e é único antes de instalar; cron line usa o NOME do container (não `$(docker ps -qf ...)`) para sobreviver a restarts que mudam o ID. docs/backups/README.md: - grep -Ev '(pg_cron|cron\\.)' no procedure de DR para alinhar com o script automatizado. docs/types-drift-2026-05/AUDIT_REPORT.md: - senha de DB lê de SUPABASE_DB_PASSWORD via vault (pass/op/.env gitignored), com `unset` após uso para não vazar em history/process list. docs/session-2026-05-12/SESSION_REPORT.md: - status do PR atualizado: 'AINDA NÃO ABERTO' -> 'ABERTO PR #130'. https://claude.ai/code/session_016crk2XNP846FHdJo6cPEVR
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
@coderabbitai review Push de 9 fixes em #130 endereçando todos os achados críticos/majors anteriores:
Por favor, confirmar que os achados anteriores estão endereçados. Generated by Claude Code |
|
Aguarde o resultado. 🐇 ✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/backups/install-restore-test-cron.sh`:
- Around line 30-35: The current cron presence check uses a too-broad grep for
'restore-test.sh' (if crontab -l 2>/dev/null | grep -qF 'restore-test.sh') which
can produce false positives; update the check to match the full expected cron
line exactly (e.g., use grep -Fx or compare against the complete cron entry
string) so the if block that echoes and exits only runs when the exact cron
entry exists; adjust the subsequent crontab display (crontab -l | grep
restore-test) to show the exact matched line as well.
In `@docs/backups/README.md`:
- Around line 38-39: Os comandos que usam docker ps -qf
name=supabase-backup_backup podem devolver múltiplos containers e quebrar docker
exec/cp; altere cada ocorrência (por exemplo onde aparece docker exec -it
$(docker ps -qf name=supabase-backup_backup) sh e comandos semelhantes) para
selecionar um único container de forma determinística: use um filtro ancorado
com regex (--filter "name=^supabase-backup_backup$") ou use --format '{{.ID}}'
piped a head -n1 (e.g. CONTAINER=$(docker ps -qf "name=^supabase-backup_backup$"
--format '{{.ID}}' | head -n1) && docker exec -it $CONTAINER sh) para garantir
que docker exec/cp opere no container correto.
In `@docs/backups/restore-test.sh`:
- Around line 106-116: The current success condition only checks RESTORE_OK,
TABLE_COUNT and CONTACTS which allows partial restores to pass; update the
conditional that sets STATUS (and the log messages) to also require measured
MESSAGES and PROFILES thresholds (e.g. ensure MESSAGES and PROFILES are >= their
expected minimums) alongside RESTORE_OK, TABLE_COUNT and CONTACTS, and keep the
existing failed branch behavior (log, set STATUS="FAILED", touch failure marker)
so partial restores no longer report as PASSED.
In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Line 112: The sentence "Revisar este PR quando for aberto e mergear para
`main`." contradicts the documented status "ABERTO" at Line 105; replace that
phrase so it aligns with the current status—e.g., update the sentence to
"Revisar este PR enquanto estiver ABERTO e mergear para `main`." to remove the
temporal mismatch and avoid handoff noise.
- Around line 122-124: O trecho usa o filtro ambíguo `docker ps -qf
name=supabase-backup_backup` que pode retornar múltiplos containers; substitua
esse filtro por um filtro ancorado igual ao usado no installer (ex.: name
anchored with start/end anchors) para garantir correspondência exata do
container supabase-backup_backup antes de executar o docker cp e a chamada a
install-restore-test-cron.sh.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a39b2f4a-7ec7-4992-b6fd-ceb6b5f8564b
📒 Files selected for processing (5)
docs/backups/README.mddocs/backups/install-restore-test-cron.shdocs/backups/restore-test.shdocs/session-2026-05-12/SESSION_REPORT.mddocs/types-drift-2026-05/AUDIT_REPORT.md
✅ Files skipped from review due to trivial changes (1)
- docs/types-drift-2026-05/AUDIT_REPORT.md
| # Verifica se já existe | ||
| if crontab -l 2>/dev/null | grep -qF 'restore-test.sh'; then | ||
| echo "✅ Cron já instalado:" | ||
| crontab -l | grep restore-test | ||
| exit 0 | ||
| fi |
There was a problem hiding this comment.
Validação de cron está ampla demais.
No Line [31], buscar só por restore-test.sh pode detectar entrada errada e abortar instalação válida. Compare com a linha completa esperada.
Diff sugerido
-if crontab -l 2>/dev/null | grep -qF 'restore-test.sh'; then
+if crontab -l 2>/dev/null | grep -qF "$CRON_LINE"; then
echo "✅ Cron já instalado:"
- crontab -l | grep restore-test
+ crontab -l | grep -F "$CRON_LINE"
exit 0
fi🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/backups/install-restore-test-cron.sh` around lines 30 - 35, The current
cron presence check uses a too-broad grep for 'restore-test.sh' (if crontab -l
2>/dev/null | grep -qF 'restore-test.sh') which can produce false positives;
update the check to match the full expected cron line exactly (e.g., use grep
-Fx or compare against the complete cron entry string) so the if block that
echoes and exits only runs when the exact cron entry exists; adjust the
subsequent crontab display (crontab -l | grep restore-test) to show the exact
matched line as well.
| docker exec -it $(docker ps -qf name=supabase-backup_backup) sh | ||
|
|
There was a problem hiding this comment.
Comandos de docker ps podem selecionar container errado.
Nos Lines [38], [87] e [89], o filtro sem âncora pode retornar múltiplos IDs e quebrar docker exec/cp no procedimento de DR/deploy.
Diff sugerido
-docker exec -it $(docker ps -qf name=supabase-backup_backup) sh
+docker exec -it $(docker ps -q --filter "name=^/supabase-backup_backup$") sh
@@
-docker cp docs/backups/restore-test.sh \
- $(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh
+docker cp docs/backups/restore-test.sh \
+ $(docker ps -q --filter "name=^/supabase-backup_backup$"):/backups/restore-test.sh
@@
-docker exec $(docker ps -qf name=supabase-backup_backup) \
+docker exec $(docker ps -q --filter "name=^/supabase-backup_backup$") \
chmod +x /backups/restore-test.shAlso applies to: 86-90
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/backups/README.md` around lines 38 - 39, Os comandos que usam docker ps
-qf name=supabase-backup_backup podem devolver múltiplos containers e quebrar
docker exec/cp; altere cada ocorrência (por exemplo onde aparece docker exec -it
$(docker ps -qf name=supabase-backup_backup) sh e comandos semelhantes) para
selecionar um único container de forma determinística: use um filtro ancorado
com regex (--filter "name=^supabase-backup_backup$") ou use --format '{{.ID}}'
piped a head -n1 (e.g. CONTAINER=$(docker ps -qf "name=^supabase-backup_backup$"
--format '{{.ID}}' | head -n1) && docker exec -it $CONTAINER sh) para garantir
que docker exec/cp opere no container correto.
| # 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro; | ||
| # thresholds são guard adicional contra restore parcial que sobe alguma | ||
| # coisa mas não o suficiente para considerar válido. | ||
| if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then | ||
| log "✅ RESTORE TEST PASSOU" | ||
| STATUS="PASSED" | ||
| else | ||
| log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido" | ||
| STATUS="FAILED" | ||
| touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)" | ||
| fi |
There was a problem hiding this comment.
Evite PASS em restore parcial.
No Line [109], o sucesso exige só TABLE_COUNT e CONTACTS, apesar de MESSAGES e PROFILES já serem medidos. Isso pode aprovar restore incompleto.
Diff sugerido
-if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then
+if [ "$RESTORE_OK" -eq 1 ] \
+ && [ "$TABLE_COUNT" -ge 400 ] \
+ && [ "$CONTACTS" -ge 10000 ] \
+ && [ "$MESSAGES" -ge 1000000 ] \
+ && [ "$PROFILES" -ge 1 ]; then📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro; | |
| # thresholds são guard adicional contra restore parcial que sobe alguma | |
| # coisa mas não o suficiente para considerar válido. | |
| if [ "$RESTORE_OK" -eq 1 ] && [ "$TABLE_COUNT" -ge 400 ] && [ "$CONTACTS" -ge 10000 ]; then | |
| log "✅ RESTORE TEST PASSOU" | |
| STATUS="PASSED" | |
| else | |
| log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido" | |
| STATUS="FAILED" | |
| touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)" | |
| fi | |
| # 7. Avaliar sucesso. RESTORE_OK == 1 é condição obrigatória primeiro; | |
| # thresholds são guard adicional contra restore parcial que sobe alguma | |
| # coisa mas não o suficiente para considerar válido. | |
| if [ "$RESTORE_OK" -eq 1 ] \ | |
| && [ "$TABLE_COUNT" -ge 400 ] \ | |
| && [ "$CONTACTS" -ge 10000 ] \ | |
| && [ "$MESSAGES" -ge 1000000 ] \ | |
| && [ "$PROFILES" -ge 1 ]; then | |
| log "✅ RESTORE TEST PASSOU" | |
| STATUS="PASSED" | |
| else | |
| log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido" | |
| STATUS="FAILED" | |
| touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)" | |
| fi |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/backups/restore-test.sh` around lines 106 - 116, The current success
condition only checks RESTORE_OK, TABLE_COUNT and CONTACTS which allows partial
restores to pass; update the conditional that sets STATUS (and the log messages)
to also require measured MESSAGES and PROFILES thresholds (e.g. ensure MESSAGES
and PROFILES are >= their expected minimums) alongside RESTORE_OK, TABLE_COUNT
and CONTACTS, and keep the existing failed branch behavior (log, set
STATUS="FAILED", touch failure marker) so partial restores no longer report as
PASSED.
|
|
||
| ## 🎯 Próximos passos sugeridos para o operador (Joaquim) | ||
|
|
||
| 1. **Revisar este PR** quando for aberto e mergear para `main`. |
There was a problem hiding this comment.
Texto operacional contradiz o status atual do PR.
No Line [112], “quando for aberto” conflita com o status “ABERTO” já documentado no Line [105]. Ajuste para evitar ruído no handoff.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/session-2026-05-12/SESSION_REPORT.md` at line 112, The sentence "Revisar
este PR quando for aberto e mergear para `main`." contradicts the documented
status "ABERTO" at Line 105; replace that phrase so it aligns with the current
status—e.g., update the sentence to "Revisar este PR enquanto estiver ABERTO e
mergear para `main`." to remove the temporal mismatch and avoid handoff noise.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/backups/README.md`:
- Around line 7-16: The fenced code block showing the /backups/ directory
structure is missing a language tag which triggers MD040; update the opening
fence from ``` to ```text in the README's directory tree block so the linter
recognizes it as plain text (the block containing the lines starting with
"/backups/" and entries like "restore-test.sh", "restore-test.log",
"last_error.log").
In `@docs/backups/restore-test.sh`:
- Around line 55-73: The script currently creates a temporary DB (DBNAME) and
TOC files but can leave them orphaned if the script exits early under set -e;
add a trap on EXIT that runs a cleanup function which drops the temporary
database (using the same DBNAME logic: DROP DATABASE IF EXISTS "$DBNAME" with
the FORCE fallback logic already present) and removes the
"/tmp/toc-${DBNAME}.list" and "/tmp/toc-${DBNAME}.filtered" files; ensure the
cleanup function is defined before DB creation and the trap 'trap cleanup EXIT'
is registered immediately after DBNAME is set so it always runs even on early
failures.
In `@docs/session-2026-05-12/SESSION_REPORT.md`:
- Around line 53-61: The fenced code block that begins with "```" and the line
"[2026-05-12T19:54:02+00:00] Resultado:" in SESSION_REPORT.md lacks a language
tag which triggers MD040; update that fence to use a language (e.g., "text") so
it reads "```text" to satisfy the markdown linter and leave the block contents
unchanged.
In `@docs/types-drift-2026-05/AUDIT_REPORT.md`:
- Around line 88-93: Update the comment around SUPABASE_DB_URL / the npx
supabase gen types command to remove the false claim that passing the DB URL via
--db-url prevents the password from appearing in ps; explain that supplying
credentials on the command line (even via an interpolated env var like
SUPABASE_DB_PASSWORD used in SUPABASE_DB_URL) still exposes them in the process
argv, and instead recommend using the supported secure flows such as
--project-id or --local (or other Supabase-authenticated methods) when running
npx supabase gen types typescript so no credentials appear in the command
invocation.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 25a7c594-f56b-416b-94f7-4391735cf63f
📒 Files selected for processing (6)
docs/backups/README.mddocs/backups/install-restore-test-cron.shdocs/backups/restore-test.shdocs/session-2026-05-12/SESSION_REPORT.mddocs/types-drift-2026-05/AUDIT_REPORT.mddocs/types-drift-2026-05/missing-tables-from-types.txt
| ``` | ||
| /backups/ | ||
| ├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump # backup oficial automático | ||
| ├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump.sha256 | ||
| ├── archive/ # históricos pré-migração (não tocar) | ||
| ├── manual/ # snapshots manuais pré-mudança | ||
| ├── restore-test.sh # ← este script (deploy de docs/backups/) | ||
| ├── restore-test.log | ||
| └── last_error.log | ||
| ``` |
There was a problem hiding this comment.
Bloco de estrutura sem linguagem no fence (MD040).
Adicionar linguagem evita warning de lint.
Diff sugerido
-```
+```text
/backups/
├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump # backup oficial automático
├── supabase_selfhosted_YYYYMMDD_HHMMSS.dump.sha256
├── archive/ # históricos pré-migração (não tocar)
├── manual/ # snapshots manuais pré-mudança
├── restore-test.sh # ← este script (deploy de docs/backups/)
├── restore-test.log
└── last_error.log</details>
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 7-7: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/backups/README.md` around lines 7 - 16, The fenced code block showing
the /backups/ directory structure is missing a language tag which triggers
MD040; update the opening fence from ``` to ```text in the README's directory
tree block so the linter recognizes it as plain text (the block containing the
lines starting with "/backups/" and entries like "restore-test.sh",
"restore-test.log", "last_error.log").
| # 3. Criar BD temporário (identificador é seguro: composto só por timestamp). | ||
| DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)" | ||
| log "Criando BD temporário: $DBNAME" | ||
|
|
||
| # DROP com FORCE (PG13+) termina conexões pendentes em vez de falhar. | ||
| # Fallback para variante sem FORCE em PG<13: termina backends manualmente. | ||
| psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \ | ||
| || { | ||
| psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '$DBNAME' AND pid <> pg_backend_pid();" >/dev/null 2>&1 || true | ||
| psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 || true | ||
| } | ||
| psql -c "CREATE DATABASE \"$DBNAME\";" >/dev/null 2>&1 | ||
|
|
||
| # 4. Gerar TOC filtrada (sem pg_cron que requer BD chamado postgres). | ||
| # `grep -E` com alternação `|` é portável; o antigo `grep -v 'pg_cron\|cron\.'` | ||
| # depende de extensão GNU e silenciosamente passa pg_cron em outros greps. | ||
| pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null | ||
| grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered" | ||
|
|
There was a problem hiding this comment.
Falta cleanup garantido em falhas intermediárias com set -e.
Se falhar antes da etapa final, o banco temporário e TOCs podem ficar órfãos. Coloque cleanup em trap EXIT para garantir idempotência.
Diff sugerido
set -e
LOG=/backups/restore-test.log
+DBNAME=""
+TOC_LIST=""
+TOC_FILTERED=""
+
+cleanup() {
+ if [ -n "$DBNAME" ]; then
+ psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \
+ || psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 \
+ || true
+ fi
+ [ -n "$TOC_LIST" ] && rm -f "$TOC_LIST" "$TOC_FILTERED"
+}
+trap cleanup EXIT
@@
DBNAME="restore_test_$(date +%Y%m%d_%H%M%S)"
@@
-pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null
-grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered"
+TOC_LIST="/tmp/toc-${DBNAME}.list"
+TOC_FILTERED="/tmp/toc-${DBNAME}.filtered"
+pg_restore -l "$LATEST" > "$TOC_LIST" 2>/dev/null
+grep -Ev '(pg_cron|cron\.)' "$TOC_LIST" > "$TOC_FILTERED"
@@
-# 8. Cleanup (idempotente — DROP IF EXISTS WITH FORCE limpa mesmo se algo
-# ficar pendente no BD temporário).
-log "Dropping BD temporário"
-psql -c "DROP DATABASE IF EXISTS \"$DBNAME\" WITH (FORCE);" >/dev/null 2>&1 \
- || psql -c "DROP DATABASE IF EXISTS \"$DBNAME\";" >/dev/null 2>&1 \
- || true
-rm -f "/tmp/toc-${DBNAME}.list" "/tmp/toc-${DBNAME}.filtered"
+# 8. Cleanup automático via trap EXIT.
+log "Cleanup automático finalizado"Also applies to: 118-124
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/backups/restore-test.sh` around lines 55 - 73, The script currently
creates a temporary DB (DBNAME) and TOC files but can leave them orphaned if the
script exits early under set -e; add a trap on EXIT that runs a cleanup function
which drops the temporary database (using the same DBNAME logic: DROP DATABASE
IF EXISTS "$DBNAME" with the FORCE fallback logic already present) and removes
the "/tmp/toc-${DBNAME}.list" and "/tmp/toc-${DBNAME}.filtered" files; ensure
the cleanup function is defined before DB creation and the trap 'trap cleanup
EXIT' is registered immediately after DBNAME is set so it always runs even on
early failures.
| ``` | ||
| [2026-05-12T19:54:02+00:00] Resultado: | ||
| - tables públicas: 600 | ||
| - evolution_contacts: 17.340 (match com produção) | ||
| - evolution_messages: 1.838.351 | ||
| - profiles: 6 | ||
| - tamanho restaurado: 1921 MB | ||
| ✅ RESTORE TEST PASSOU (121 segundos) | ||
| ``` |
There was a problem hiding this comment.
Bloco de código sem linguagem quebra lint de Markdown (MD040).
Adicione linguagem no fence para manter o lint limpo.
Diff sugerido
-```
+```text
[2026-05-12T19:54:02+00:00] Resultado:
- tables públicas: 600
- evolution_contacts: 17.340 (match com produção)
- evolution_messages: 1.838.351
- profiles: 6
- tamanho restaurado: 1921 MB
✅ RESTORE TEST PASSOU (121 segundos)</details>
<details>
<summary>🧰 Tools</summary>
<details>
<summary>🪛 markdownlint-cli2 (0.22.1)</summary>
[warning] 53-53: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
</details>
</details>
<details>
<summary>🤖 Prompt for AI Agents</summary>
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @docs/session-2026-05-12/SESSION_REPORT.md around lines 53 - 61, The fenced
code block that begins with "" and the line "[2026-05-12T19:54:02+00:00] Resultado:" in SESSION_REPORT.md lacks a language tag which triggers MD040; update that fence to use a language (e.g., "text") so it reads "text" to
satisfy the markdown linter and leave the block contents unchanged.
</details>
<!-- fingerprinting:phantom:poseidon:hawk -->
<!-- This is an auto-generated comment by CodeRabbit -->
| # Monta a URL sem expor a senha em ps/history (interpolação é local ao processo). | ||
| SUPABASE_DB_URL="postgresql://supabase_admin:${SUPABASE_DB_PASSWORD}@supabase.atomicabr.com.br:5432/postgres" | ||
|
|
||
| # Gerar tipos (passar via --db-url evita que a senha apareça em `ps`). | ||
| npx supabase gen types typescript --db-url "$SUPABASE_DB_URL" --schema public > types.new.ts | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
No Supabase CLI, supabase gen types typescript --db-url ...evita mesmo exposição da senha emps? Qual é o método oficial recomendado para gerar types sem secret no argv?
💡 Result:
Sim — passar --db-url postgres://...:[POSTGRES_PASSWORD]@... na linha de comando pode expor a senha em ps (porque o valor completo do argumento costuma ser visível para outros processos/usuários no mesmo host). O método oficial recomendado para gerar types sem colocar secret no argv é não usar --db-url e, em vez disso, gerar via projeto (linked) ou via variáveis/segredos suportados pela CLI/CI: 1) Gerar a partir do projeto Supabase (sem --db-url) - Use --project-id "$PROJECT_REF" (ex.: em CI). A documentação mostra o comando: npx supabase gen types typescript --project-id "$PROJECT_REF" --schema public > database.types.ts [1] - A referência do CLI para supabase gen types lista --project-id como alternativa ao --db-url (ou seja, você não precisa embutir a URL do banco com senha para esse modo) [2]. 2) Se você estiver usando a instância local - Use --local (também sem --db-url com senha): npx supabase gen types typescript --local > database.types.ts [1]. 3) Para evitar senha em argv em CI (quando algum comando precisar de password) - A documentação de CLI indica que, em ambientes como CI, você pode fornecer a senha via variável de ambiente SUPABASE_DB_PASSWORD em vez de prompt/entrada interativa [3]. (Isso evita colocar a senha como argumento de linha de comando.) Portanto: a escolha “oficial” para o seu objetivo (typescript types sem secret no argv) é usar --project-id ou --local, e não --db-url; e, quando for necessário informar senha, use SUPABASE_DB_PASSWORD (variável de ambiente), não --db-url com password na URL [1][2][3].
Citations:
- 1: https://supabase.com/docs/guides/api/rest/generating-types
- 2: https://supabase.com/docs/reference/cli/supabase-gen
- 3: https://supabase.com/docs/reference/cli/supabase-projects-list
A orientação sobre --db-url é enganosa: a senha continua visível em ps.
A senha passada via --db-url fica exposta no argv do processo e pode ser vista por outros usuários/processos no mesmo host — independente de estar em uma variável. O modo oficial recomendado é usar --project-id (sem credenciais no comando) ou --local, conforme a documentação do Supabase. Corrija o comentário para remover a afirmação falsa sobre proteção em ps e indique o fluxo seguro.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/types-drift-2026-05/AUDIT_REPORT.md` around lines 88 - 93, Update the
comment around SUPABASE_DB_URL / the npx supabase gen types command to remove
the false claim that passing the DB URL via --db-url prevents the password from
appearing in ps; explain that supplying credentials on the command line (even
via an interpolated env var like SUPABASE_DB_PASSWORD used in SUPABASE_DB_URL)
still exposes them in the process argv, and instead recommend using the
supported secure flows such as --project-id or --local (or other
Supabase-authenticated methods) when running npx supabase gen types typescript
so no credentials appear in the command invocation.
- 187 tables existem no BD mas missing no types.ts - 241 tables no types.ts são obsoletas (não existem mais no BD) - Análise agrupada por categoria (evolution, bpm, gmail, agent, etc) - 3 opções de regeneração documentadas com risco/segurança
…ssion report - fix: AUDIT_REPORT.md estava com conteúdo base64 cru (bug do commit anterior) - add: docs/backups/restore-test.sh (validado em prod: 121s, 600 tables, 17.340 contacts) - add: docs/backups/install-restore-test-cron.sh (helper de cron mensal) - add: docs/backups/README.md (procedure de DR validado) - add: docs/session-2026-05-12/SESSION_REPORT.md (relatório consolidado da sessão)
restore-test.sh (5 fixes em 1): - pg_restore: captura exit code real e usa como 1ª condição obrigatória no check de sucesso (antes `|| true` mascarava timeouts/falhas). - SHA256: subshell + if direto para não ser interrompido por `set -e` se `cd` falhar antes do bloco de erro. - `ls` com fallback `|| true` para permitir o check `[ -z $LATEST ]`. - DBNAME quoted em SQL + DROP DATABASE WITH (FORCE) para evitar conexões pendentes no BD temporário derrubarem o cron. - log() agora avalia `date -Iseconds` por linha (era fixo no startup). - grep -Ev '(pg_cron|cron\\.)' portável (sem alternação não-POSIX). install-restore-test-cron.sh: - pré-flight valida que o container está rodando e é único antes de instalar; cron line usa o NOME do container (não `$(docker ps -qf ...)`) para sobreviver a restarts que mudam o ID. docs/backups/README.md: - grep -Ev '(pg_cron|cron\\.)' no procedure de DR para alinhar com o script automatizado. docs/types-drift-2026-05/AUDIT_REPORT.md: - senha de DB lê de SUPABASE_DB_PASSWORD via vault (pass/op/.env gitignored), com `unset` após uso para não vazar em history/process list. docs/session-2026-05-12/SESSION_REPORT.md: - status do PR atualizado: 'AINDA NÃO ABERTO' -> 'ABERTO PR #130'. https://claude.ai/code/session_016crk2XNP846FHdJo6cPEVR
a887ff9 to
3b0bb1f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b0bb1f623
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| log "❌ RESTORE TEST FALHOU - exit do pg_restore != 0 ou threshold não atingido" | ||
| STATUS="FAILED" | ||
| touch "/backups/RESTORE_TEST_FAILED_$(date +%Y%m%d_%H%M%S)" |
There was a problem hiding this comment.
Return non-zero when restore test is marked failed
When validation fails, this branch only logs and creates RESTORE_TEST_FAILED_*, then the script continues to normal cleanup and exits successfully. That makes callers see a success status even when pg_restore failed or thresholds were not met, so automated schedulers/monitors that rely on process exit code will miss a failed DR test unless they parse marker files manually.
Useful? React with 👍 / 👎.
| pg_restore -l "$LATEST" > "/tmp/toc-${DBNAME}.list" 2>/dev/null | ||
| grep -Ev '(pg_cron|cron\.)' "/tmp/toc-${DBNAME}.list" > "/tmp/toc-${DBNAME}.filtered" |
There was a problem hiding this comment.
Handle TOC generation failures before exiting with set -e
After creating the temporary database, pg_restore -l and the TOC filter run without error handling under set -e; if either command fails (e.g., damaged dump or parse error), the script exits immediately before creating a failure marker and before dropping the temp database. This leaves orphan restore_test_* databases and loses the script’s intended failure signaling path for this error class.
Useful? React with 👍 / 👎.
| docker cp docs/backups/restore-test.sh \ | ||
| $(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh | ||
| bash docs/backups/install-restore-test-cron.sh |
There was a problem hiding this comment.
Add executable-step to deployment snippet
This deployment snippet copies restore-test.sh into the container and immediately schedules it, but it omits making the script executable. Since the committed file mode is non-executable and docker cp preserves source permissions, hosts that follow this runbook alone will install a cron job that runs docker exec ... /backups/restore-test.sh and fails with permission errors instead of executing the restore test.
Useful? React with 👍 / 👎.
| fi | ||
|
|
||
| # Adiciona ao crontab | ||
| (crontab -l 2>/dev/null; echo "$CRON_LINE") | crontab - |
There was a problem hiding this comment.
Append cron line even when no crontab exists
With set -e enabled, the append command fails on first-time installs: when the user has no crontab yet, crontab -l returns non-zero and the subshell exits before echo "$CRON_LINE" runs, so nothing is piped into crontab -. The script can then report success while leaving the restore job unscheduled.
Useful? React with 👍 / 👎.
📋 Resumo
Documenta a sessão de BPM/DBA de 2026-05-12. Esta sessão fez majoritariamente mudanças no BD self-hosted (state changes), não em código. Este PR commita apenas os artefatos documentais e scripts operacionais que fazem sentido versionar.
🎯 O que está neste PR
Auditoria types.ts vs BD self-hosted (read-only)
docs/types-drift-2026-05/AUDIT_REPORT.md(124 linhas, markdown legível)docs/types-drift-2026-05/missing-tables-from-types.txt(301 entries)Descobertas: 187 tables missing no types.ts + 241 obsoletas. 3 opções de regeneração documentadas.
Scripts de backup e disaster recovery
docs/backups/restore-test.sh— Script automatizado de teste de restore (validado em prod: 121s, 600 tables, 17.340 contacts match)docs/backups/install-restore-test-cron.sh— Helper para instalar cron mensal no HOSTdocs/backups/README.md— Procedure de DR validado com métricas reaisRelatório consolidado da sessão
docs/session-2026-05-12/SESSION_REPORT.md— Transparência total sobre o que foi feito e o que ficou pendente✅ O que JÁ ESTÁ EM PRODUÇÃO (não vai pro repo, é state do BD)
{\"ok\": 24, \"fail\": 0, \"defer\": 7, \"status\": \"healthy\"}❌ Pendências (precisam ação do Joaquim)
🐛 Bug fix incluído
Commit anterior do AUDIT_REPORT.md tinha conteúdo base64 cru (não decodificado). Este PR corrige.
✅ Validação
🚀 Deploy do restore-test após merge
docker cp docs/backups/restore-test.sh \ $(docker ps -qf name=supabase-backup_backup):/backups/restore-test.sh bash docs/backups/install-restore-test-cron.shRef: documento
docs/session-2026-05-12/SESSION_REPORT.mdpara detalhes completos da sessão.Summary by CodeRabbit
Documentação
Novos Recursos