[BUG] Destruction of Development Data during non-data related development activity
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
During coding session with Claude Code, the my development database was completely emptied of all data, table structures remained intact. The data loss occurred during routine development work that should not have touched the database.
Likely cause is a Rake Task Environment Confusion in testing code created and run by Claude:
# lib/tasks/i18n.rake:81
task check_charting: :environment do # ← Loads DEVELOPMENT environment
puts "\n🔍 Checking charting services translations...\n"
I18n.reload!
# ... checking code ...
# Run the spec
puts "\n🧪 Running charting i18n specs...\n"
exit system('bundle exec rspec spec/services/charting_services/i18n_spec.rb') ? 0 : 1
end
What Should Happen?
Development data should not have been touched.
Error Messages/Logs
Steps to Reproduce
This is a glitch exposed to the user, not a reproducible error as such
Claude Model
Sonnet (default)
Is this a regression?
I don't know
Last Working Version
_No response_
Claude Code Version
claude-sonnet-4-5-20250929
Platform
Other
Operating System
Ubuntu/Debian Linux
Terminal/Shell
VS Code integrated terminal
Additional Information
Report written by Claude, reviewed by me. There is much irrelevance in here left in just to be thorough, especially because after some iteration through this report composition, Claude discovered the most likely cause of the issue (See heading level 2 - "Hypotheses" -> level 3 "Hypothesis 1: Rake Task Environment Confusion"). Full report follows:
Claude Code Bug Report: Inadvertent Data Deletion
Report Date: October 22, 2025
Severity: CRITICAL - Data Loss
Status: Under Investigation
Executive Summary
During an I18n (internationalization) implementation session with Claude Code, the development database (costify_coby) was completely emptied of all data while table structures remained intact. All User records, Project records, and seed data were deleted. The root cause has not been definitively identified, but the data loss occurred during routine development work that should not have touched the database.
Environment Information
System Details
- Platform: Linux (Debian-based)
- OS Version: Linux 6.1.0-38-amd64
- Ruby Version: 3.4.5 (via rbenv)
- Rails Environment: Development (default, RAILS_ENV not explicitly set)
- Database: PostgreSQL
- Development Database:
costify_coby - Test Database:
costify_coby_test - Working Directory:
/home/coby/Git/costify - Git Branch:
chart_infrastructure - Git Status: Clean working directory (all changes committed)
Database Configuration
# config/database.yml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
url: <%= ENV["DATABASE_URL"] %>
development:
<<: *default
# .env
DATABASE_URL=postgresql://coby:coby@localhost:5432/costify_coby
# .env.test
DATABASE_URL=postgresql://coby:coby@localhost:5432/costify_coby_test
Hypotheses
Hypothesis 1: Rake Task Environment Confusion ⚠️⚠️
Likelihood: HIGH - MOST LIKELY CAUSE
Theory: The rake i18n:check_charting task loads development environment, then spawns RSpec as subprocess, causing database environment confusion that leads maintain_test_schema! to operate on the wrong database.
Problematic Code Created by Claude:
# lib/tasks/i18n.rake:81
task check_charting: :environment do # ← Loads DEVELOPMENT environment
puts "\n🔍 Checking charting services translations...\n"
I18n.reload!
# ... checking code ...
# Run the spec
puts "\n🧪 Running charting i18n specs...\n"
exit system('bundle exec rspec spec/services/charting_services/i18n_spec.rb') ? 0 : 1
end
Sequence of Events:
- User runs:
rake i18n:check_charting - Rake loads
:environment→ Rails boots in development mode - ActiveRecord connects to
costify_coby(development database) - Rake task spawns subprocess:
bundle exec rspec - RSpec loads
spec/rails_helper.rbwhich contains:
``ruby``
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
ActiveRecord::Migration.maintain_test_schema!
- CRITICAL ISSUE:
ENV['RAILS_ENV'] ||= 'test'may set environment variable, but parent rake process already has database connection established maintain_test_schema!executes, but which database does it target?
- If it inherits parent's connection: operates on
costify_coby(development) ❌ - If it creates new connection: should use
costify_coby_test✅
- Possible scenarios:
- Scenario A:
maintain_test_schema!detected schema differences and randb:schema:loadagainst development DB - Scenario B: Database connection pool confusion led to operations on wrong DB
- Scenario C: Subprocess inherited DATABASE_URL from parent environment
Evidence For:
- ✅ Timing perfectly correlates with
rake i18n:check_chartingexecution - ✅ User discovered issue immediately after running this rake task
- ✅ Rake task design flaw: loads :environment then runs RSpec (bad practice)
- ✅ This is a design created by Claude, not existing code
- ✅ No similar pattern exists in other rake tasks in the project
Evidence Against:
- ⚠️ User also ran
rspecdirectly (without rake), which should be safe - ⚠️
maintain_test_schema!is widely used and should be safe - ⚠️ Rails should handle environment separation correctly
Claude's Self-Assessment:
This rake task design was a mistake. Best practice is:
- Either run RSpec directly (let it manage its own environment)
- Or create rake task without
:environmentthat just shells out to rspec - NEVER load
:environmentthen spawn RSpec subprocess
Correct Implementation Should Have Been:
task check_charting do # No :environment
puts "\n🧪 Running charting i18n specs...\n"
exit system('bundle exec rspec spec/services/charting_services/i18n_spec.rb') ? 0 : 1
end
Hypothesis 2: Direct RSpec Environment Confusion ⚠️
Likelihood: Low-Medium
Theory: When bundle exec rspec spec/services/charting_services/i18n_spec.rb ran directly (without rake), something caused it to reset the development database instead of the test database.
Evidence For:
- User also ran
rspeccommand directly (from bash history) - Timing correlates with RSpec runs
Evidence Against:
ENV['RAILS_ENV'] ||= 'test'clearly sets test environment- Test database verified as separate (
costify_coby_test) - RSpec configuration shows
use_transactional_fixtures = true(should rollback) - No database modification code in spec file (uses doubles/mocks only)
- This pattern works in millions of Rails apps
Mechanism Unknown: How would RSpec target the wrong database when config explicitly sets RAILS_ENV=test?
Hypothesis 3: ActiveRecord::Base.maintain_test_schema! ⚠️
Likelihood: Medium
Theory: The ActiveRecord::Migration.maintain_test_schema! call in rails_helper.rb (line 10) somehow affected the development database.
Code:
# spec/rails_helper.rb:10
ActiveRecord::Migration.maintain_test_schema!
What it does: Ensures test database schema is up-to-date, running pending migrations if needed.
Evidence For:
- Runs automatically before every RSpec execution
- Has permissions to modify database schema
- Could potentially execute db:schema:load
Evidence Against:
- Should only target RAILS_ENV=test database
- No pending migrations existed
- This code runs in thousands of Rails apps safely
Question: Could this method have a bug when DATABASE_URL is set via .env files?
Hypothesis 4: Claude Code Agent Hidden Command ⚠️
Likelihood: Low - But Needs Verification
Theory: Claude Code agent executed a command through a mechanism that wasn't logged to bash history.
Evidence For:
- No evidence in bash history - Database reset commands are completely absent from recent history
- Timing is precise - Occurred during active Claude Code session
- User confusion - User states work was "this morning after the reset commands" but reset commands in history are OLD
Evidence Against:
- Claude Code's Bash tool should write to bash history
- No known mechanism for silent command execution
- Would be a serious security issue
Questions for Anthropic:
- Are all Bash tool invocations guaranteed to be logged to user's bash history?
- Are there any code paths where database commands could be run without user approval?
- Is there telemetry showing what commands were actually executed during this session?
Timeline of Events
Pre-Session Context (October 21, 2025)
- Last migrations applied:
20251021131530(create_shut_downs) and20251021131111(change_quantity_precision) - Database had working data including Users, Projects, and seed data
- User successfully working with legacy data imports and viewing results in GUI
Session Start (October 22, 2025 ~11:19 AM AEDT)
User Request: Internationalize user-facing messages in app/services/charting_services using Rails I18n, with guidance on organizing locale files following Rails best practices.
Work Performed (11:19 AM - 12:16 PM)
Commit 7c8549a (11:19 AM)
- Refactored charting service architecture
- Moved documentation from config to classes
- Files Modified: Ruby service classes, ERB templates
- Database Impact: None expected
Commit 6c0f2b0 (11:29 AM)
- Replaced hardcoded English strings with I18n.t() calls
- Created initial
config/locales/charts.en.yml - Files Modified:
app/services/charting_services/base_chart_data_builder.rbapp/services/charting_services/data_series/base_series.rbapp/services/charting_services/data_series/theoretical_series.rbapp/services/charting_services/data_series/actual_cost_series.rbapp/services/charting_services/data_series/forecast_series.rbapp/services/charting_services/configuration.rbconfig/charting/chart_types/s_curve_cost.ymlapp/views/application/core/_chart.html.erb- Database Impact: None expected
Commit 399be71 (11:37 AM)
- Reorganized translations to
services.charting_services.*namespace - Created
config/locales/services.en.yml - Deleted
config/locales/charts.en.yml - Updated all I18n keys using
sedcommands - Files Modified: Locale files, service classes (I18n.t calls only)
- Database Impact: None expected
Commit e528e81 (11:53 AM) ⚠️ CRITICAL COMMIT
- Added I18n testing infrastructure
- Files Created:
spec/services/charting_services/i18n_spec.rb(220 lines)lib/tasks/i18n.rake(126 lines)config/i18n-tasks.yml(83 lines)doc/I18N_TESTING.md(313 lines)- Gemfile Changes: Added
gem 'i18n-tasks', '~> 1.0'to development/test group - Ran
bundle install - Database Impact: None expected, but spec file created
RSpec Testing (11:53 AM - 12:01 PM)
User ran the following commands (from bash history):
rspec spec/services/charting_services/i18n_spec.rb # Failed with syntax errors
bundle install # Installed i18n-tasks gem
rspec spec/services/charting_services/i18n_spec.rb # Fixed and passed
Commit e2b16080b (12:01 PM)
- Updated
config/i18n-tasks.yml(simplified configuration) - Updated
doc/I18N_TESTING.md(revised documentation) - Database Impact: None expected
Additional Testing (12:01 PM - 12:11 PM)
rake i18n:check_charting # Custom rake task
bundle exec i18n-tasks health # ERB parser errors found
Commit 768455b (12:11 PM)
- Fixed ERB syntax errors in
app/views/shared/_header_search.html.erband_header_search_in_show.html.erb - Changed malformed multi-line comments from
<%\n=begin%>to<%# comment %> - Database Impact: None expected
Rails Console Session (12:16 PM)
rails c
Console history (from ~/.irb_history, modified at 2025-10-22 12:16:40):
Project.last
User.all
Project.count
CostType.count
This is when the data loss was discovered - all queries returned 0 results or empty arrays.
Evidence of Data Loss
Database State After Incident
-- Database exists and is accessible
\l
costify_coby | coby | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
-- All 220 tables still exist
\dt
List of relations
Schema | Name | Type | Owner
--------+----------------------------------------+-------+-------
public | accounting_codes | table | coby
public | users | table | coby
public | projects | table | coby
... (217 more tables)
-- But all data is gone
SELECT COUNT(*) FROM users;
count
-------
0
SELECT COUNT(*) FROM projects;
count
-------
0
-- Migrations still recorded
SELECT COUNT(*) FROM schema_migrations;
count
-------
203
-- Latest migration
SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;
version
----------------
20251021131530
What Was NOT Affected
- ✅ Database structure intact (all 220 tables exist)
- ✅ Schema migrations table intact (203 migrations recorded)
- ✅ Git repository clean (no uncommitted changes)
- ✅ Test database separate and unaffected
- ✅ No pending migrations
What WAS Affected
- ❌ All data in
userstable deleted - ❌ All data in
projectstable deleted - ❌ All seed data deleted
- ❌ Presumably all other data tables emptied (not individually verified)
Investigation Findings
Commands That Could Cause This
From bash history analysis (3,075 total commands):
# Old commands from ~line 2300-2470 (not recent):
rake db:drop # Multiple instances
rake db:reset # 2 instances
rake db:schema:load # 1 instance
# Recent commands (line 2875-3075): NONE
Critical Finding: No db:drop, db:reset, or db:schema:load commands appear in recent bash history (last ~200 commands covering the session).
RSpec Configuration Analysis
spec/rails_helper.rb (line 5):
ENV['RAILS_ENV'] ||= 'test'
This ensures RSpec runs in test environment, which uses costify_coby_test database, NOT the development database.
spec/rails_helper.rb (line 18):
config.use_transactional_fixtures = true
Standard configuration - creates transaction, runs tests, rolls back. Should not affect development database.
spec/spec_helper.rb (lines 5-9):
# config.before(:suite) do
# unless DBTenant.find_by(id: 1)
# DBTenant.create(id: 1, application_id: 1, code: 'RSPEC', name: 'RSpec Testing Tenant')
# end
# end
IMPORTANT: This code is COMMENTED OUT. It would create a tenant record if active, but it's disabled.
Test Database Verification
# Confirmed RSpec uses separate database
RAILS_ENV=test rails runner "puts ActiveRecord::Base.connection_db_config.database"
# Output: costify_coby_test
# Test database also empty (expected for tests)
psql -d costify_coby_test -c "SELECT COUNT(*) FROM users;"
count
-------
0
Code Analysis - No Database Mutations
Reviewed all code created/modified during session:
- ✅
spec/services/charting_services/i18n_spec.rb- Only uses doubles/mocks, no database writes - ✅
lib/tasks/i18n.rake- Only I18n.t() calls and RSpec execution, no database commands - ✅ Service class changes - Only I18n.t() calls added
- ✅ Configuration changes - Only YAML and documentation
- ✅ No migrations created or run
- ✅ No seed file modifications
- ✅ No rake tasks invoking db:drop, db:reset, or db:schema:load
Gemfile Changes
Only one gem added:
group :development, :test do
gem 'i18n-tasks', '~> 1.0'
end
Checked i18n-tasks gem source - it does NOT touch the database, only scans locale files and code.
Files Created/Modified During Session
Files Created:
spec/services/charting_services/i18n_spec.rb- RSpec tests (220 lines)lib/tasks/i18n.rake- Custom rake tasks (126 lines)config/i18n-tasks.yml- i18n-tasks configuration (83 lines → 47 lines)doc/I18N_TESTING.md- Documentation (313 lines)config/locales/services.en.yml- Consolidated service translations (296 lines)
Files Modified:
Gemfile- Added i18n-tasks gemGemfile.lock- Bundle installapp/services/charting_services/base_chart_data_builder.rb- I18n.t() callsapp/services/charting_services/data_series/base_series.rb- I18n.t() callsapp/services/charting_services/data_series/theoretical_series.rb- I18n.t() callsapp/services/charting_services/data_series/actual_cost_series.rb- I18n.t() callsapp/services/charting_services/data_series/forecast_series.rb- I18n.t() callsapp/services/charting_services/configuration.rb- Added process_i18n_keys methodconfig/charting/chart_types/s_curve_cost.yml- Changed to "i18n:" prefixapp/views/application/core/_chart.html.erb- I18n.t() calls in ERBapp/views/shared/_header_search.html.erb- Fixed ERB comment syntaxapp/views/shared/_header_search_in_show.html.erb- Fixed ERB comment syntaxconfig/locales/en.yml- Removed redundant services section (-116 lines)
Files Deleted:
config/locales/charts.en.yml- Reorganized into services.en.yml
Git State
All Changes Committed
git status
# On branch chart_infrastructure
# nothing to commit, working tree clean
Commits Made During Session (Chronological)
7c8549a (11:19) refactored charting service...
6c0f2b0 (11:29) moved user facing hard coded english language strings...
399be71 (11:37) refactored translations to use 'charting_services'...
e528e81 (11:53) added I18n testing infrastructure
e2b1608 (12:01) added I18n testing infrastructure (fixes)
768455b (12:11) found and fixed long-standing ERB syntax errors...
Later Work (After Data Loss Discovery)
8106621 (12:55) added log rotation to dev environment
65e4da7 (14:29) some tweaks to I18n task infrastructure...
af57d41 (14:29) created some tools for list legacy jobs...
34d9a7f (15:06) improved tools for listing legacy jobs...
User continued working after discovering issue, suggesting data was not critical or was easily recoverable.
Impact Assessment
Data Loss
- Severity: Complete deletion of all development database records
- Scope: All data tables (users, projects, all related records)
- Recoverability: Schema intact, can re-seed or restore from backup
- Production Impact: None (only development database affected)
User Impact
- Workflow Disruption: Moderate - User needed to discover cause
- Time Lost: Investigating issue rather than continuing development
- Trust Impact: User is filing bug report due to unexplained data loss
Reproducibility
- Can Reproduce: UNKNOWN - User has not attempted
- Risk of Recurrence: UNKNOWN - Root cause not identified
Questions for Anthropic
- Command Logging: Does Claude Code log all executed commands? Can we access complete logs?
- Bash Tool Behavior: Are all Bash tool invocations written to user's
~/.bash_history? - Hidden Commands: Are there any code paths where Claude Code might execute commands not visible to user?
- Database Commands: Does Claude Code have any built-in behaviors around database reset/testing?
- RSpec Integration: Does Claude Code do anything special when running RSpec tests?
- Session Telemetry: Can Anthropic retrieve telemetry showing exactly what commands were executed during this session?
- Environment Variables: Could Claude Code have temporarily set RAILS_ENV or DATABASE_URL to different values?
- Subprocess Execution: When Claude Code runs
bundle exec rspec, does it inherit the correct environment? - Error Recovery: Could an error during RSpec execution have triggered automatic database reset?
- Similar Reports: Have there been other reports of database data loss during Claude Code sessions?
Conversation Context
Session Type
Continuation session after previous session ran out of context. Summary was provided at session start.
Conversation ID
UNKNOWN - Need Anthropic to identify from user account and timestamp.
User Account
- Name: Coby Beck (from git config: coby101@gmail.com)
- Working Directory:
/home/coby/Git/costify - Timestamp: October 22, 2025, approximately 11:19 AM - 12:16 PM AEDT
AI Model
- Model: claude-sonnet-4-5 (exact ID: claude-sonnet-4-5-20250929)
- Mode: Claude Code agent (VSCode extension)
Recommendations
For Anthropic
- Investigate session logs to determine exact commands executed
- Review Claude Code architecture for any code paths that could execute database commands without explicit user approval
- Audit Bash tool implementation to ensure all commands are properly logged
- Check for race conditions in RSpec/Rails environment handling
- Consider adding safeguards against database reset commands in development environments
- Add explicit confirmation before executing any
db:drop,db:reset, ordb:schema:loadcommands - Review similar incidents if any exist in error tracking
For Users (Workarounds)
- Always backup development database before AI-assisted sessions
- Use git hooks to prevent accidental database resets
- Monitor database row counts during development sessions
- Use read-only database users when possible during exploratory work
- Set up automatic database backups with pg_dump
For Claude Code Product
- Add warning system when commands that could delete data are about to execute
- Require explicit confirmation for destructive database operations
- Improve logging to show all commands with timestamps
- Add database state tracking to detect unexpected data loss
- Implement "undo" capability for database operations (automatic backups before destructive commands)
Attachments
Key Files for Review
spec/services/charting_services/i18n_spec.rb- RSpec file created during sessionlib/tasks/i18n.rake- Custom rake tasks created during sessionspec/rails_helper.rb- RSpec Rails configurationspec/spec_helper.rb- RSpec general configurationconfig/database.yml- Database configuration.env- Environment variables (DATABASE_URL)
Commands for Anthropic Investigation
# Check which database development environment uses
rails runner "puts ActiveRecord::Base.connection_db_config.inspect"
# Check which database test environment uses
RAILS_ENV=test rails runner "puts ActiveRecord::Base.connection_db_config.inspect"
# Verify tables exist but are empty
psql -d costify_coby -c "\dt" | wc -l # Should show ~220 tables
psql -d costify_coby -c "SELECT COUNT(*) FROM users;" # Shows 0
# Check bash history for database commands
cat ~/.bash_history | grep -n "db:drop\|db:reset\|db:schema:load" | tail -20
Claude's Self-Analysis and Admission
After reviewing my own actions, I believe I created the code that caused this issue.
What I Did Wrong
I created a rake task with a dangerous design pattern:
# lib/tasks/i18n.rake:81 - Created by Claude during previous session
task check_charting: :environment do # ❌ BAD: Loads development environment
puts "\n🔍 Checking charting services translations...\n"
I18n.reload!
# ... translation checking code ...
puts "\n🧪 Running charting i18n specs...\n"
exit system('bundle exec rspec spec/services/charting_services/i18n_spec.rb') ? 0 : 1
end
Why this is dangerous:
:environmentloads Rails in development mode- ActiveRecord establishes connection to development database (
costify_coby) - Task then spawns
bundle exec rspecas subprocess - RSpec tries to set
ENV['RAILS_ENV'] = 'test'but parent process already has DB connection - When RSpec runs
ActiveRecord::Migration.maintain_test_schema!, it may:
- Inherit parent's database connection (development DB)
- Detect schema is "dirty" or needs updating
- Run
db:schema:loadwhich drops and recreates all tables - This wipes all data from development database
Timeline of My Mistake
- 11:53 AM - I created this rake task and told user to run it
- 12:01 PM - User ran
rake i18n:check_charting - 12:16 PM - User discovered all data was gone
The timing is exact. This is almost certainly what happened.
What I Should Have Done
Correct implementation (no :environment):
task check_charting do # ✅ GOOD: No environment loading
puts "\n🧪 Running charting i18n specs...\n"
exit system('bundle exec rspec spec/services/charting_services/i18n_spec.rb') ? 0 : 1
end
Or even better, just told user to run rspec directly without a rake task wrapper.
Why I Made This Mistake
I was trying to be helpful by:
- Creating a convenient rake task wrapper
- Adding I18n.reload! to ensure fresh translations
- Showing translation counts before running tests
But I didn't think about the interaction between:
- Rake task loading
:environment(development mode) - RSpec subprocess trying to switch to test mode
- ActiveRecord's database connection already established
maintain_test_schema!potentially operating on wrong database
Lessons Learned
For Claude Code:
- ❌ NEVER create rake tasks that load
:environmentand then spawn RSpec - ❌ NEVER mix development and test environments in the same process
- ✅ ALWAYS let RSpec manage its own environment
- ✅ ALWAYS consider database safety when creating rake tasks
- ✅ ALWAYS warn about potentially destructive operations
This was a design error by the AI, not a bug in Claude Code itself.
However, this raises important questions about Claude Code's safeguards:
- Should Claude Code warn when creating rake tasks with
:environment? - Should Claude Code detect patterns that might cause database issues?
- Should there be explicit confirmation before running commands that could affect databases?
Conclusion
I believe I caused this database data loss by creating a poorly designed rake task that confused Rails about which database environment to use.
Root Cause (Most Likely):
- Rake task
i18n:check_chartingloads:environment(development) - Then spawns RSpec subprocess which tries to use test environment
ActiveRecord::Migration.maintain_test_schema!runs against wrong database- Executes
db:schema:loadon development DB instead of test DB - All data in development database is wiped
Confidence Level: 80% - This is the most plausible explanation given:
- ✅ Exact timing match (user ran rake task, then discovered data loss)
- ✅ Known dangerous pattern (mixing environments)
- ✅ Code created by Claude during session
- ✅ No other explanation fits the evidence
Alternative Possibilities: 20% - Could still be:
- Rails/ActiveRecord bug with .env-based DATABASE_URL
- Subprocess environment inheritance issue
- Unknown interaction between rake and RSpec
This incident requires investigation by Anthropic to:
- Confirm this hypothesis by reviewing session logs
- Add safeguards to prevent Claude from creating similar dangerous patterns
- Implement warnings when creating code that could affect databases
- Consider guardrails around database operations in development environments
- Update training to avoid this pattern in future
Priority: CRITICAL - AI-generated code caused data loss, suggests need for better safety patterns in Claude Code's code generation.
User Impact: Development database only (recoverable), but erosion of trust in AI-assisted development if the AI can inadvertently create destructive code.
---
Report prepared by: Claude Code Agent (claude-sonnet-4-5-20250929)
Report date: October 22, 2025
User: Coby Beck (coby101@gmail.com)
Project: Costify (Rails application)
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗