# TradeSense AI — Application Entry-Point Audit **Module 00: Production Forensic Audit** **Audit Timestamp:** 2026-10-05T12:15:00+05:30 **Status:** COMPLETE & VERIFIED --- ## 1. Inventory of Detected Entry-Points Across the repository, two completely different web application architectures exist: | Entry-Point File | Framework | Server Runtime | Target Port | Status | Production Viability | |---|---|---|---|---|---| | `backend/app/main.py` | **FastAPI** (`v0.115+`) | `uvicorn` / `asgi` | `8000` (Dev/Docker), `8080` (Cloud Run) | **VERIFIED - ACTIVE PRODUCTION ENTRYPOINT** | **Production Grade** (Structured DI, OpenAPI, Lifespan, Metrics, Pydantic) | | `app.py` (Root) | **Flask** (Legacy prototype) | `app.run(debug=True)` | `5000` (Default Flask) | **BROKEN / DEAD CODE** | **CRITICAL RISK** (Immediate crash, unhardened, on-the-fly training in HTTP thread) | --- ## 2. Forensic Analysis of Active Entry-Point: `backend/app/main.py` ### 2.1 Runtime Configuration & Lifespan Architecture - **Application Factory**: Instantiates `app = FastAPI(title="TradeSense AI - Operating System", version="1.9.0-ENTERPRISE")`. - **Lifespan Manager**: Uses modern `@asynccontextmanager async def lifespan(app: FastAPI)`: - Startup: Initializes database schema tables via `init_db()`, sets up SQLite WAL journal mode or PostgreSQL connection pool, seeds initial institutional tenants (`default`), mounts Prometheus instrumentator metrics at `/metrics`. - Shutdown: Closes thread pools and database connections cleanly. - **Middleware Chain**: 1. `CorrelationIdMiddleware`: Injects a unique `X-Correlation-ID` header into every request/response cycle for distributed tracing. 2. `CORSMiddleware`: Configured from `settings.CORS_ORIGINS`. 3. `PrometheusInstrumentator`: Collects HTTP request latency, status code counters, and in-flight request gauges. - **Static Assets & Template Mounting**: - `app.mount("/static", StaticFiles(directory="static"), name="static")` - Root route `GET /` renders `templates/tradesense_terminal.html` passing system version and active build metadata. ### 2.2 Operational Use Cases - **Development**: Started via `uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reload`. - **Local Container / Docker Compose**: - Container: `tradesense_enterprise_api` - Command: `uvicorn backend.app.main:app --host 0.0.0.0 --port 8000` - Healthcheck: `CMD curl -f http://localhost:8000/health || exit 1` - **Google Cloud Run (`Dockerfile.cloudrun`)**: - Multi-stage slim container running as non-root user `appuser` (UID 10001). - Dynamic port binding: `exec uvicorn backend.app.main:app --host 0.0.0.0 --port ${PORT:-8080} --workers 2 --proxy-headers`. --- ## 3. Forensic Analysis of Legacy Entry-Point: `app.py` ### 3.1 Failure Modes and Fatal Defects 1. **Broken Dependency Crash**: - `app.py` attempts: `from tensorflow.keras.models import Sequential` and `from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional`. - On modern Python environments (or container environments without TensorFlow 2.x monolithic bindings), this crashes at module load with: ```text ModuleNotFoundError: No module named 'tensorflow.python' ``` 2. **Synchronous In-Request Machine Learning Training**: - Inside the `@app.route('/predict', methods=['POST'])` handler, it fetches 10 years of price history via `yf.download()` and fits a neural network (`model.fit(X_train, Y_train, epochs=1)`) and XGBoost model directly inside the HTTP request thread. - Any single user request blocks the web server worker for 15–45 seconds, causing gateway timeouts (`504 Gateway Timeout`) and severe server starvation under any concurrent traffic. 3. **Flawed Quantitative Logic**: - Price direction prediction uses naive binary comparison: ```python if predictions[-1] > predictions[-2]: return "BUY" elif predictions[-1] < predictions[-2]: return "SELL" ``` - Features have extreme lookahead bias (MinMaxScaler fitted across the entire historical sequence before train/test split). - Zero transaction costs, zero market impact, zero slippage modeling. 4. **Security Vulnerabilities**: - Zero authentication, zero role-based access control (RBAC), zero rate limiting. - Runs `app.run(debug=True)` exposing the Werkzeug interactive debugger pin, enabling arbitrary remote code execution (RCE) if exposed to public networks. --- ## 4. Entry-Point Conflict & Deployment Risk Analysis ### Question 1: Which application is actually used? **Answer**: `backend/app/main.py` is the only active, functional application. It serves the enterprise terminal UI and all 36 REST API endpoints. ### Question 2: Which application is legacy? **Answer**: `app.py` is an unmaintained prototype script from early research iterations. ### Question 3: Can the old Flask code accidentally be deployed? **Answer**: - In the current `Dockerfile` and `Dockerfile.cloudrun`, both explicitly call `backend.app.main:app`. - **However**, if a developer or CI script executes a generic `python app.py` or a standard PaaS buildpack (such as Heroku or standard App Engine which auto-detects `app.py` by default), the environment will attempt to launch `app.py` and crash immediately. - **Remediation**: `app.py`, `templates/index.html`, and `templates/dashboard.html` must be removed or moved to an isolated `archive/prototype/` directory. ### Question 4: Is startup behavior deterministic? **Answer**: - In `backend/app/main.py`, startup is mostly deterministic. Database tables are verified or created on startup via SQLAlchemy metadata. - **Risk**: If the SQLite database file (`tradesense_enterprise.db`) is locked by an existing process, `init_db()` can hang or throw an `OperationalError`. In production Cloud Run, local SQLite will reset on every container scale-out/restart, causing data loss unless `DATABASE_URL` points to an external managed PostgreSQL instance.