The user wants a "multi-layer chaos test" that simulates failures at different levels of a software system, specifically: Browser API failures, Network faults, and Model errors.
1. Deconstruct the Request:
- Goal: Create a comprehensive chaos testing strategy/implementation.
- Layers:
- Browser API failures: Things like
navigator.geolocation failing, localStorage being full, getUserMedia denying permission, WebWorkers crashing.
- Network faults: Latency, packet loss, connection drops, DNS failures, 500 errors from APIs.
- Model errors: This usually implies machine learning models (predicting wrong, taking too long) or perhaps business logic state corruption, but given the context of "browser" and "network," it likely refers to the AI/LLM layer often present in modern apps (e.g., streaming token failures, hallucinations, rate limits). Let's assume an AI/LLM context for "Model errors" as it's the most relevant interpretation in current tech trends.
2. Strategy & Architecture:
I need to provide a framework or a specific code example. A single script won't cover all bases easily unless I simulate an environment. A Node.js/Playwright or Puppeteer setup is standard for this, but a pure client-side Javascript injection strategy (using a library like toxiproxy or simple wrappers) might be more accessible for immediate implementation.
Approach: I will design a modular Javascript/Typescript class structure that can be integrated into a test suite (like Playwright/Cypress) or used as a standalone script to override global objects.
3. Layer 1: Browser API Chaos
- Mechanism: Override
window or navigator properties.
- Failures:
localStorage quota exceeded.
fetch returning specific errors (overlaps with network, but strictly client-side context).
getUserMedia rejection.
- Random crashes in async functions.
4. Layer 2: Network Chaos
- Mechanism: Intercept
XMLHttpRequest and fetch.
- Failures:
- Random delays (latency).
- Random connection resets.
- HTTP 5xx/4xx status codes.
- Malformed JSON responses.
5. Layer 3: Model Errors (AI/LLM focus)
- Mechanism: Since the model is usually accessed via an API, this overlaps with Network, but the content of the failure is specific.
- Failures:
- Streaming token interruptions (SSE disconnect).
- Content policy violations (refusal responses).
- Context window exceeded.
- Invalid JSON output from the model.
6. Engineering the Solution:
I will create a "ChaosInjector" class. It needs to be configurable (probability of failure, types of errors).
- Structure:
ChaosEngine: Main controller.
BrowserMonkey: Patches browser APIs.
NetworkGremlin: Patches fetch/XHR.
ModelSimulator: Specific handling for AI model responses.
7. Drafting the Code (Mental or Scratchpad):
- Network:
const originalFetch = window.fetch;
window.fetch = (...args) => {
if (Math.random() < 0.5) return Promise.reject(new Error('Network Error'));
// simulate delay
return new Promise(r => setTimeout(() => r(originalFetch(...args)), 2000));
}
- Browser:
// Override localStorage
const originalSetItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
if (Math.random() < 0.1) throw new DOMException("Quota exceeded");
return originalSetItem.call(this, key, value);
}
- Model:
If the app uses a specific SDK (like OpenAI's), I should mock that. If it's generic, I'll simulate a streaming response that cuts off midway.
8. Refining the Output:
The prompt asks to "Engineer" a test. This implies:
- Architecture: How to structure it.
- Implementation: The actual code.
- Execution: How to run it.
I will provide a comprehensive solution using a Playwright (or generic JS injection) approach because it allows controlling the browser context. I'll write a "Chaos Injector" client-side script that can be injected into the page.
9. Specific Considerations for "Model Errors":
Since "Model" is ambiguous, I will interpret it as "Backend/AI Model".
- Scenario: The UI waits for a stream.
- Fault: The stream stops sending
[DONE] or throws a 429 Rate Limit.
10. Structuring the Response:
- Introduction: Define the scope.
- The Architecture: The "Chaos Registry" pattern.
- The Code (The Core Request): A unified
ChaosMonkey class.
- Network:
fetch wrapper.
- Browser:
navigator/storage wrapper.
- Model: Response payload mutation (truncated JSON, hallucinated invalid schemas).
- Integration: How to use this in Playwright/Cypress.
- Reporting: How to verify the app survived (didn't crash, showed error boundary).
Self-Correction during drafting:
Initial thought: Just use Toxiproxy.
Correction: Toxiproxy requires infrastructure setup. The user likely wants code-level injection for a "browser API" context. Client-side monkey patching is more direct for "Browser API failures" than a network proxy. I will implement a purely client-side "Gremlin" script that can be injected.
Detailed Implementation Plan:
- Class
ChaosOrchestrator.
- Method
injectNetworkFaults(): Wraps fetch. random 500s, timeouts.
- Method
injectBrowserAPIFaults(): Wraps localStorage, geolocation.
- Method
injectModelFaults(): Detects JSON responses looking like AI output and mangles them or simulates partial streams.
Let's write the code. I will focus on a modular, probability-based approach.
Layer 1: Network
- Intercept
window.fetch.
- Add random latency.
- Randomly reject the promise.
- Randomly return HTTP 500/502/503.
Layer 2: Browser
navigator.geolocation.getCurrentPosition: Always return error callback.
localStorage.setItem: Randomly throw QuotaExceededError.
window.alert: Block it (some apps hang if alerts are spammed).
Layer 3: Model (The tricky one)
- Since I don't know the specific model API, I will hook into
fetch again but look for patterns (e.g., endpoints containing "chat" or "completion").
- Simulated Failures:
- "Context Length Exceeded" error payload.
- Truncated JSON stream (simulate network cut during AI response).
- "Content Filter" triggered.
Final Polish:
Ensure the code is safe (can be toggled off) and logs what it's doing so the engineer can see what failed.
Let's assemble.
- File 1:
chaos-engine.js (The injection logic)
- File 2:
test-runner.js (The Playwright/Puppeteer script to inject it)
This is a comprehensive engineering solution for a multi-layer chaos test. This solution is designed to be injected into a web application (via DevTools console, a bookmarklet, or a E2E testing framework like Playwright/Cypress) to validate the resilience of the UI.
The Architecture
We will build a ChaosOrchestrator that manages three distinct "Gremlin" modules:
- Network Gremlin: Intercepts
fetch/XHR to simulate HTTP failures, latency, and packet loss.
- Browser Gremlin: Overrides native Browser APIs (Storage, Geolocation, Media) to simulate permission denials and hardware faults.
- Model Gremlin: Specifically targets data logic (simulating backend validation errors, null pointers, or AI hallucinations) by mutating JSON responses on the fly.
The Implementation
You can copy and paste the following block directly into your browser's console while running your local application, or bundle it into your testing suite.
/**
* CHAOS ORCHESTRATOR
* A multi-layer fault injection framework for web applications.
*/
class ChaosOrchestrator {
constructor(config = {}) {
this.config = {
networkFailureRate: 0.1, // 10% of requests fail
latencyMs: [100, 3000], // Random latency between 100ms and 3s
browserFaultRate: 0.2, // 20% chance of browser API errors
modelMutationRate: 0.15, // 15% chance of data corruption
verbose: true,
...config
};
this.originals = {
fetch: window.fetch,
setItem: window.Storage.prototype.setItem,
getGeo: navigator.geolocation.getCurrentPosition.bind(navigator.geolocation)
};
this.active = false;
}
log(layer, message, data) {
if (!this.config.verbose) return;
console.log(`%c[CHAOS - ${layer}]`, 'color: white; background: red; font-weight: bold;', message, data || '');
}
/**
* LAYER 1: NETWORK FAULTS
* Intercepts fetch, introduces latency, HTTP errors, and connection resets.
*/
injectNetworkFaults() {
const self = this;
window.fetch = async function(...args) {
const [url, options] = args;
// 1. Simulate Latency
const delay = Math.floor(Math.random() * (self.config.latencyMs[1] - self.config.latencyMs[0])) + self.config.latencyMs[0];
await new Promise(r => setTimeout(r, delay));
// 2. Simulate Random Connection Reset
if (Math.random() < self.config.networkFailureRate) {
self.log('NETWORK', 'Simulating Connection Reset', url);
return Promise.reject(new TypeError('Failed to fetch (Network Error)'));
}
// 3. Execute Request
const response = await self.originals.fetch(...args);
// 4. Simulate HTTP 5xx Server Errors
if (Math.random() < self.config.networkFailureRate) {
self.log('NETWORK', 'Simulating HTTP 500', url);
return new Response(JSON.stringify({ error: "Internal Server Error injected by Chaos" }), {
status: 500,
statusText: 'Internal Server Error',
headers: { 'Content-Type': 'application/json' }
});
}
return response;
};
this.log('NETWORK', 'Fault injection activated.');
}
/**
* LAYER 2: BROWSER API FAULTS
* Simulates hardware failures, quota errors, and permission denials.
*/
injectBrowserFaults() {
const self = this;
// 1. LocalStorage Quota Exceeded
window.Storage.prototype.setItem = function(key, value) {
if (Math.random() < self.config.browserFaultRate) {
self.log('BROWSER', 'Simulating Quota Exceeded', key);
throw new DOMException("QuotaExceededError: Chaos simulation");
}
return self.originals.setItem.call(this, key, value);
};
// 2. Geolocation Permission Denied / Timeout
navigator.geolocation.getCurrentPosition = function(success, error, options) {
if (Math.random() < self.config.browserFaultRate) {
self.log('BROWSER', 'Simulating Geolocation Failure');
if (error) {
return error({ code: 1, message: "User denied Geolocation" }); // Code 1 = PERMISSION_DENIED
}
return;
}
return self.originals.getGeo(success, error, options);
};
// 3. Randomly block Notifications
if (window.Notification) {
const originalPermission = Notification.permission;
Object.defineProperty(Notification, 'permission', {
get: function() {
if (Math.random() < self.config.browserFaultRate) {
self.log('BROWSER', 'Spoofing Notification Permission Denied');
return 'denied';
}
return originalPermission;
}
});
}
this.log('BROWSER', 'Fault injection activated.');
}
/**
* LAYER 3: MODEL ERRORS (DATA MUTATION)
* Intercepts JSON responses and corrupts data structure to test UI resilience.
*/
injectModelFaults() {
const self = this;
// We need to wrap the Response object prototype to intercept .json() calls
const originalJson = Response.prototype.json;
Response.prototype.json = async function() {
const data = await originalJson.call(this);
if (Math.random() > self.config.modelMutationRate) {
return data; // Pass through cleanly
}
self.log('MODEL', 'Corrupting JSON response', data);
// Strategy A: Return Empty (Simulate backend lookup failure)
if (Math.random() < 0.3) return {};
// Strategy B: Nullify critical fields (Simulate DB join failure)
if (Array.isArray(data)) {
return data.map(item => ({ ...item, id: null, name: undefined }));
}
// Strategy C: Type Mismatch (Simulate schema drift)
// Turns an ID number into a string, or an array into an object
if (typeof data === 'object' && data !== null) {
const keys = Object.keys(data);
const randomKey = keys[Math.floor(Math.random() * keys.length)];
data[randomKey] = "CORRUPTED_DATA";
}
return data;
};
this.log('MODEL', 'Fault injection activated.');
}
/**
* Activates all layers of chaos.
*/
start() {
if (this.active) return;
this.active = true;
console.warn("🔥 CHAOS ENGINE STARTED 🔥");
this.injectNetworkFaults();
this.injectBrowserFaults();
this.injectModelFaults();
}
/**
* Restores original browser behavior.
*/
stop() {
window.fetch = this.originals.fetch;
window.Storage.prototype.setItem = this.originals.setItem;
navigator.geolocation.getCurrentPosition = this.originals.getGeo;
// Note: Response.prototype.json restoration is tricky without keeping a deeper reference,
// refreshing the page is the safest 'stop' for prototype mutations.
this.active = false;
console.log("❄️ CHAOS ENGINE STOPPED (Restore recommended: Refresh page)");
}
}
// --- EXECUTION ---
// 1. Initialize with configuration
const chaos = new ChaosOrchestrator({
networkFailureRate: 0.15, // 15% network fail chance
latencyMs: [200, 2000], // Laggy network
browserFaultRate: 0.25, // 25% browser API fail chance
modelMutationRate: 0.20 // 20% data corruption chance
});
// 2. Start the test
chaos.start();
// To stop: chaos.stop(); (then refresh page for full cleanup)
Implementation Details
1. Network Layer (The Pipe)
We override the global window.fetch.
- Latency: We wrap every promise in a
setTimeout to simulate slow "G" networks (3G/Edge).
- Connection Reset: We randomly reject the promise before the request technically "finishes." This tests if your UI shows a generic "Network Error" toast or crashes.
- Server Errors: We allow the request to finish but swap the
Response object with a 500 error.
2. Browser Layer (The Environment)
We attack the window and navigator objects.
- Storage: We wrap
setItem. If your app relies on saving user preferences or tokens, this forces your "Storage Full" fallback logic (or crash).
- Geolocation: We force the error callback. This ensures your map UI handles the "User denied permission" state gracefully instead of spinning infinitely.
- Permissions: We mock the
Notification.permission getter to return 'denied'.
3. Model Layer (The Logic)
This is often the most dangerous layer. Modern apps expect JSON schemas to remain stable.
- Prototype Pollution: We override
Response.prototype.json.
- Corruption Strategies:
- Empty Object: Returns
{} instead of a list of items. Does your UI show "No results" or crash trying to .map undefined?
- Nullification: Returns the object but sets
id: null. Does your React key prop break?
- Type Flipping: Changes a boolean
isAuthenticated: true to a string "CORRUPTED".
How to Interpret Results
When running this script, your application should ideally degrade gracefully. Here is what to look for:
- No White Screens of Death (WSD): Even if the model returns corrupted JSON, your React/ErrorBoundary should catch rendering errors.
- User Feedback: If the network fails, a toast notification should appear.
- Fallback UI: If
localStorage fails, the app should default to in-memory storage or continue read-only without crashing the sign-in flow.
- Retry Logic: If the network returns 502, check if your HTTP client (Axios/Ky) attempts a retry (if configured).