provider: AjaxSpeaks

license: Evaluation use only. Not licensed for model training or redistribution without agreement.

domain: ecommerce

split: train

problem_statement: processCartItem() in registry accesses cart[index] without checking if the index is within bounds. If cart items are removed (e.g., concurrent stock check removes out-of-stock items), the index becomes stale and access returns undefined, causing a crash or undefined behavior. Fixed by adding bounds and nullity checks.

buggy_source:
// Enterprise Component: SysShield | Ticket: TICKET-5733 | Trace: INC-553
function processCartItem(userCart_89, index) {
    // BUG: Direct array access without bounds check
    // Items may have been removed concurrently or by other logic
    const item = userCart_89[index];
    return {
        itemId: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
    };
}
module.exports = { processCartItem };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for SysShield (TICKET-5733)
const assert = require('assert');
const { processCartItem } = require('../src/handler');

describe('CHECKOUT_OUT_OF_BOUNDS Fix Test', function() {
    it('should handle invalid index gracefully', function() {
        const userCart_89 = [{ id: 'ITEM-001', name: 'Widget', price: 9.99, quantity: 2 }];
        const result = processCartItem(userCart_89, 5);
        assert.ok(result.error, 'Should return error for out-of-bounds index');
        assert.ok(result.error.includes('not found'));
    });

    it('should process valid userCart_89 dataPayload_8', function() {
        const userCart_89 = [
            { id: 'ITEM-001', name: 'Widget', price: 9.99, quantity: 2 },
            { id: 'ITEM-002', name: 'Gadget', price: 24.99, quantity: 1 },
        ];
        const result = processCartItem(userCart_89, 1);
        assert.strictEqual(result.itemId, 'ITEM-002');
        assert.strictEqual(result.price, 24.99);
    });

    it('should handle negative index', function() {
        const userCart_89 = [{ id: 'ITEM-001', name: 'Widget', price: 9.99, quantity: 2 }];
        const result = processCartItem(userCart_89, -1);
        assert.ok(result.error, 'Should return error for negative index');
    });
});

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,8 +1,13 @@
 // Enterprise Component: SysShield | Ticket: TICKET-5733 | Trace: INC-553
 function processCartItem(userCart_89, index) {
-    // BUG: Direct array access without bounds check
-    // Items may have been removed concurrently or by other logic
+    // FIX: Bounds check before accessing array
+    if (index < 0 || index >= userCart_89.length) {
+        return { error: 'Item not found at index ' + index };
+    }
     const item = userCart_89[index];
+    if (!item) {
+        return { error: 'Item is null or removed' };
+    }
     return {
         itemId: item.id,
         name: item.name,

reference_solution:
// Enterprise Component: SysShield | Ticket: TICKET-5733 | Trace: INC-553
function processCartItem(userCart_89, index) {
    // FIX: Bounds check before accessing array
    if (index < 0 || index >= userCart_89.length) {
        return { error: 'Item not found at index ' + index };
    }
    const item = userCart_89[index];
    if (!item) {
        return { error: 'Item is null or removed' };
    }
    return {
        itemId: item.id,
        name: item.name,
        price: item.price,
        quantity: item.quantity,
    };
}
module.exports = { processCartItem };

test_command: node --test tests/bug.test.js

text: We have three tickets in the last hour: checkout fails with 'something went wrong', and one says they were charged for a different item than in their basket. Anyone else seeing this?

text: Same on social. A user said their basket showed two items but they were charged for one. They want a refund.

text: Checkout error rate is up about 0.2% over the last 30 minutes. Not huge, but it's an anomaly. What items are affected?

text: Looks random — t-shirts, mugs, one laptop. No common brand or category.

text: Could it be a promo code? The laptop order had a 10% off code.

text: Two of three had no promo. One had gift wrap. Not about codes.

text: Any particular platform? I’m pulling errors by client.

text: Mixed: iOS, Android, desktop. Most on web checkout.

text: Do we have any workaround? Can they pay with PayPal instead?

text: Retry sometimes works. We're telling them to refresh and try again. Wrong-charge one is still open.

text: I'll dig into checkout logs. We haven't deployed anything today, right?

text: No deploy. But we did have a stock re-sync job run at :45. Back in 10 after I look at the logs.

text: Stock re-sync removes out-of-stock items from active baskets. If it ran mid-checkout, the contents could shift.


domain: gaming

problem_statement: purchaseItem() multiplies unit price by a caller-supplied quantity without validating it. Submitting a negative quantity yields a negative cost, which passes the funds check and then increases the player's balance — an unlimited currency mint. Fixed by requiring a positive integer quantity.

buggy_source:
// Enterprise Component: CloudCart | Ticket: TICKET-2935 | Trace: INC-874
function purchaseItem(account, itemPrice, quantity) {
            // BUG: quantity is never validated. A negative quantity makes the
            // charge negative, crediting the player instead of debiting them.
            const cost = itemPrice * quantity;
            if (account.balance < cost) {
                return { ok: false, reason: 'insufficient funds' };
            }
            account.balance = account.balance - cost;
            return { ok: true, balance: account.balance };
        }
        module.exports = { purchaseItem };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for CloudCart (TICKET-2935)
const assert = require('assert');
        const { purchaseItem } = require('../src/handler');
        describe('STORE_NEGATIVE_QUANTITY_CREDIT', function() {
            it('should reject a negative quantity instead of crediting the account', function() {
                const account = { balance: 1000 };
                const result = purchaseItem(account, 120, -5);
                assert.strictEqual(result.ok, false);
                assert.strictEqual(account.balance, 1000,
                    'balance must be untouched by a rejected purchase');
            });
            it('should charge correctly for a valid purchase', function() {
                const account = { balance: 1000 };
                const result = purchaseItem(account, 120, 2);
                assert.strictEqual(result.ok, true);
                assert.strictEqual(account.balance, 760);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,7 +1,9 @@
 // Enterprise Component: CloudCart | Ticket: TICKET-2935 | Trace: INC-874
 function purchaseItem(account, itemPrice, quantity) {
-            // BUG: quantity is never validated. A negative quantity makes the
-            // charge negative, crediting the player instead of debiting them.
+            // FIX: require a positive whole quantity before pricing anything.
+            if (!Number.isInteger(quantity) || quantity < 1) {
+                return { ok: false, reason: 'invalid quantity' };
+            }
             const cost = itemPrice * quantity;
             if (account.balance < cost) {
                 return { ok: false, reason: 'insufficient funds' };

reference_solution:
// Enterprise Component: CloudCart | Ticket: TICKET-2935 | Trace: INC-874
function purchaseItem(account, itemPrice, quantity) {
            // FIX: require a positive whole quantity before pricing anything.
            if (!Number.isInteger(quantity) || quantity < 1) {
                return { ok: false, reason: 'invalid quantity' };
            }
            const cost = itemPrice * quantity;
            if (account.balance < cost) {
                return { ok: false, reason: 'insufficient funds' };
            }
            account.balance = account.balance - cost;
            return { ok: true, balance: account.balance };
        }
        module.exports = { purchaseItem };

text: Players are saying they bought the starter pack and got gems instead of losing them. Anyone else seeing this?

[User] LiveOps

text: Yep, we have tickets. Two players in the last hour. Same thing — balance went up after purchase.

text: I pulled the purchase events. There are about 30 affected transactions in the last 30 minutes. Balance increased in all of them.

text: Some of the players are worried they'll be banned. What do we tell them?

text: Don't ban anyone yet. We're still figuring out if this is a payment glitch or something on our side.

text: The affected orders all have an unusual item count — like the number of items in the order is off.

text: Should we take the starter pack down while we investigate?

text: Already done. Starter pack is disabled in the store. Nobody can buy it right now.

text: In the data, the balance only goes up when the item count is weird. If the count is normal, the balance goes down as expected.

text: Thanks. Engineering can jump in now if anyone's around.

text: I'll take a look. Can you send me the raw order details for one of the affected players?

text: Just sent you one. The order has a unit price and an item quantity. The total is negative in the logs, which matches the balance going up.

text: Negative total? That's normally a refund or a reversal. Maybe the payment provider is sending us a credit instead of a charge?


domain: energy

split: test

problem_statement: usageDelta() subtracts the previous register reading from the current one with no wraparound handling. When the meter passes its maximum and returns to zero the delta goes sharply negative, and the billing run either credits the customer or rejects the read. Fixed by detecting the wrap and adding the rollover span.

buggy_source:
// Enterprise Component: CurisTech | Ticket: TICKET-3887 | Trace: INC-453
function usageDelta(previousReading, currentReading, meterMax) {
            // BUG: a mechanical register wraps to zero at meterMax. Subtracting
            // directly yields a large negative delta for the billing period
            // that spans the rollover.
            return currentReading - previousReading;
        }
        module.exports = { usageDelta };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for CurisTech (TICKET-3887)
const assert = require('assert');
        const { usageDelta } = require('../src/handler');
        describe('METER_ROLLOVER_NEGATIVE_USAGE', function() {
            const METER_MAX = 999999;
            it('should compute positive usage across a register rollover', function() {
                const d = usageDelta(999979, 30, METER_MAX);
                assert.strictEqual(d, 51);
            });
            it('should never report negative usage', function() {
                const d = usageDelta(999979, 30, METER_MAX);
                assert.ok(d > 0, 'usage must be positive, got ' + d);
            });
            it('should compute a normal in-period delta', function() {
                const d = usageDelta(100, 175, METER_MAX);
                assert.strictEqual(d, 75);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,8 +1,9 @@
 // Enterprise Component: CurisTech | Ticket: TICKET-3887 | Trace: INC-453
 function usageDelta(previousReading, currentReading, meterMax) {
-            // BUG: a mechanical register wraps to zero at meterMax. Subtracting
-            // directly yields a large negative delta for the billing period
-            // that spans the rollover.
-            return currentReading - previousReading;
+            // FIX: detect the wrap and account for the register rolling over.
+            if (currentReading >= previousReading) {
+                return currentReading - previousReading;
+            }
+            return (meterMax - previousReading) + currentReading + 1;
         }
         module.exports = { usageDelta };

reference_solution:
// Enterprise Component: CurisTech | Ticket: TICKET-3887 | Trace: INC-453
function usageDelta(previousReading, currentReading, meterMax) {
            // FIX: detect the wrap and account for the register rolling over.
            if (currentReading >= previousReading) {
                return currentReading - previousReading;
            }
            return (meterMax - previousReading) + currentReading + 1;
        }
        module.exports = { usageDelta };

text: We've got a problem: several meters are showing negative usage for the last billing period. Invoices went out with credits.

text: Can confirm. We have customers calling about invoices that say they used negative energy. That's not a thing.

text: I'm at one of the sites now. The meter's physical display shows a number that's gone down since last month, so the system read it as 'usage went backwards'.

text: It's not just that site. I'm seeing it on at least 15 meters across three regions.

text: We already sent the statements. Legal wants to know how many customers are affected and whether we can reissue.

text: Mechanically the meter is fine. I checked connections, swapped a test meter, readings still come back lower than the previous one.

text: Just joined. What's the current status?

text: We're trying to figure out if this is a meter hardware failure or something in our billing data. The numbers are just wrong.

text: So far it's only residential and small commercial, no large industrial. Doesn't make it better.

text: Some of these meters were read automatically, some manually. Both show the same pattern: this month's read is below last month's.

text: Hold on — are these readings all coming in as smaller numbers, or are some of them exactly zero or weird values?

text: The common thing is the current reading is lower than the previous reading. Some are a lot lower, like the meter reset to near zero.

text: I'd say it's a firmware bug in this meter model. We have three different firmware versions though.

text: We need to know if we can trust the previous months' invoices. If those were right, then it's not the meter hardware.

text: I pulled the raw readings for the affected accounts. The previous reading is always a large number, and the current reading is a much smaller number. But the small numbers aren't all near zero — they're all over the place.


domain: logistics

problem_statement: totalManifestWeight() parses each declared pallet weight with parseInt, discarding the fractional kilograms. Across a full trailer the manifest under-states the payload, so an axle-weight check that reads this total can clear a load that is actually over the legal limit. Fixed by parsing the decimal value.

buggy_source:
// Enterprise Component: DevPulse | Ticket: TICKET-8250 | Trace: INC-771
function totalManifestWeight(recordEntries_74) {
            // BUG: parseInt discards the fractional part of each declared
            // weight, so the manifest under-reports the true payload.
            return recordEntries_74.reduce(function (sum, item) {
                return sum + parseInt(item.weightKg, 10);
            }, 0);
        }
        module.exports = { totalManifestWeight };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for DevPulse (TICKET-8250)
const assert = require('assert');
        const { totalManifestWeight } = require('../src/handler');
        describe('MANIFEST_WEIGHT_TRUNCATION', function() {
            it('should sum declared weights without truncating decimals', function() {
                const total = totalManifestWeight([
                    { sku: 'PAL-1', weightKg: '7.3' },
                    { sku: 'PAL-2', weightKg: '9.2' }
                ]);
                assert.ok(Math.abs(total - 16.5) < 1e-9,
                    'expected 16.5 but got ' + total);
            });
            it('should not report the truncated integer total', function() {
                const total = totalManifestWeight([
                    { sku: 'PAL-1', weightKg: '7.3' },
                    { sku: 'PAL-2', weightKg: '9.2' }
                ]);
                assert.notStrictEqual(total, 16);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,9 +1,8 @@
 // Enterprise Component: DevPulse | Ticket: TICKET-8250 | Trace: INC-771
 function totalManifestWeight(recordEntries_74) {
-            // BUG: parseInt discards the fractional part of each declared
-            // weight, so the manifest under-reports the true payload.
+            // FIX: parse the full decimal weight.
             return recordEntries_74.reduce(function (sum, item) {
-                return sum + parseInt(item.weightKg, 10);
+                return sum + parseFloat(item.weightKg);
             }, 0);
         }
         module.exports = { totalManifestWeight };

reference_solution:
// Enterprise Component: DevPulse | Ticket: TICKET-8250 | Trace: INC-771
function totalManifestWeight(recordEntries_74) {
            // FIX: parse the full decimal weight.
            return recordEntries_74.reduce(function (sum, item) {
                return sum + parseFloat(item.weightKg);
            }, 0);
        }
        module.exports = { totalManifestWeight };

text: We've got a load that passed the yard scale but got flagged at a roadside check. Driver says the roadside weight is 1,400 lbs higher than our ticket.

text: That's the third one this week. Our scale was calibrated last month, so I don't know what to tell you.

text: This is a compliance problem. If we can't trust our weights, we're exposed to fines. Do we know why the numbers disagree?

text: Customer is asking which weight is right. I said we're investigating.

text: We weighed it twice before it left. Same number both times. Roadside is somehow higher.

text: Is it the same trailers or routes? I want to see if there's a pattern before we assume anything.

text: No pattern. Mixed trailers, different states.

text: Back in 10 - need to grab the scale logs.

text: Let's pull the paperwork for all three and compare side by side with the inspection reports.

text: Just saw this thread. Can someone recap? Are we comparing our manifest totals against the roadside scale printouts?

text: Yes. I can share the numbers if that helps.

text: Here they are: manifests say 44,000 / 44,100 / 43,900. Roadside says 45,200 / 45,300 / 45,100. So about 1,200-1,400 higher.

text: The gap varies, which makes me think it's not a simple calibration offset. Let me look at how we compute the manifest weight.


domain: travel

split: val

problem_statement: seatsAvailable() subtracts only confirmed bookings from the cabin total and ignores seats under a temporary payment hold. During checkout the same seat is offered to another customer, producing oversold flights that surface only at the gate. Fixed by subtracting held seats as well.

buggy_source:
// Enterprise Component: OmniCare | Ticket: TICKET-9382 | Trace: INC-995
function seatsAvailable(inventory) {
            // BUG: seats on temporary hold are still counted as available, so
            // the same seat can be sold to a second customer while the first
            // is completing payment.
            return inventory.total - inventory.booked;
        }
        module.exports = { seatsAvailable };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for OmniCare (TICKET-9382)
const assert = require('assert');
        const { seatsAvailable } = require('../src/handler');
        describe('HELD_SEAT_AVAILABILITY_OVERCOUNT', function() {
            it('should exclude held seats from availability', function() {
                const n = seatsAvailable({ total: 180, booked: 60, held: 15 });
                assert.strictEqual(n, 105);
            });
            it('should equal total minus booked when nothing is held', function() {
                const n = seatsAvailable({ total: 180, booked: 60, held: 0 });
                assert.strictEqual(n, 120);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,8 +1,7 @@
 // Enterprise Component: OmniCare | Ticket: TICKET-9382 | Trace: INC-995
 function seatsAvailable(inventory) {
-            // BUG: seats on temporary hold are still counted as available, so
-            // the same seat can be sold to a second customer while the first
-            // is completing payment.
-            return inventory.total - inventory.booked;
+            // FIX: a held seat is not available until the hold expires.
+            const held = inventory.held || 0;
+            return inventory.total - inventory.booked - held;
         }
         module.exports = { seatsAvailable };

reference_solution:
// Enterprise Component: OmniCare | Ticket: TICKET-9382 | Trace: INC-995
function seatsAvailable(inventory) {
            // FIX: a held seat is not available until the hold expires.
            const held = inventory.held || 0;
            return inventory.total - inventory.booked - held;
        }
        module.exports = { seatsAvailable };

text: Is anyone else seeing the booking page show seats that the gate says are held? Passenger just got to the gate with a confirmed seat and was told it was already taken.

text: That's the second one today. We're going to have to start compensating people.

text: Saw the alert on the seat mismatch dashboard. Looking into it.

text: It's not just at the gate — the app says available, but when they try to check in, it fails.

text: Are we talking about the same flight? This was LAX->JFK, flight 214.

text: For 214, the booking site shows 4 open seats, but the gate says only 2 are not held. So we're showing 2 extra.

text: And we just sold one of those 'extra' seats ten minutes ago. Now that passenger is going to get bumped.

text: We've got three more flights today that could be hit. Can we pull those listings off sale until we understand?


domain: iot

problem_statement: isOverTemp() compares a Celsius sensor reading against a limit configured in Fahrenheit without converting either value. Because the Fahrenheit number is numerically larger, the over-temperature alarm stays silent through the entire real danger band and only trips at roughly twice the intended threshold. Fixed by converting the reading before comparison.

buggy_source:
// Enterprise Component: ApexHealth | Ticket: TICKET-8101 | Trace: INC-619
function isOverTemp(readingCelsius, limitFahrenheit) {
            // BUG: the sensor reports Celsius but the configured alarm limit is
            // Fahrenheit. Comparing them directly means the alarm only fires
            // far past the real threshold.
            return readingCelsius > limitFahrenheit;
        }
        module.exports = { isOverTemp };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for ApexHealth (TICKET-8101)
const assert = require('assert');
        const { isOverTemp } = require('../src/handler');
        describe('THERMAL_UNIT_MISMATCH', function() {
            const LIMIT_F = 122;
            it('should raise the alarm for a Celsius reading above the limit', function() {
                assert.strictEqual(isOverTemp(55, LIMIT_F), true);
            });
            it('should stay silent for a reading well below the limit', function() {
                assert.strictEqual(isOverTemp(30, LIMIT_F), false);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,8 +1,7 @@
 // Enterprise Component: ApexHealth | Ticket: TICKET-8101 | Trace: INC-619
 function isOverTemp(readingCelsius, limitFahrenheit) {
-            // BUG: the sensor reports Celsius but the configured alarm limit is
-            // Fahrenheit. Comparing them directly means the alarm only fires
-            // far past the real threshold.
-            return readingCelsius > limitFahrenheit;
+            // FIX: convert the reading to the limit's unit before comparing.
+            const readingFahrenheit = (readingCelsius * 9 / 5) + 32;
+            return readingFahrenheit > limitFahrenheit;
         }
         module.exports = { isOverTemp };

reference_solution:
// Enterprise Component: ApexHealth | Ticket: TICKET-8101 | Trace: INC-619
function isOverTemp(readingCelsius, limitFahrenheit) {
            // FIX: convert the reading to the limit's unit before comparing.
            const readingFahrenheit = (readingCelsius * 9 / 5) + 32;
            return readingFahrenheit > limitFahrenheit;
        }
        module.exports = { isOverTemp };

text: Anyone else seeing thermal readings way off on the latest batch? Techs are pulling their hair out comparing to handheld probes.

text: Weird. Which batch exactly? And how off are we talking?

text: Batch 7 of the new deploy. Readings are like 20-30 degrees high on the dashboard compared to the probe. Unit itself feels fine.

text: Is it all readings or just some? And does it happen at a specific time of day?

text: Seems random. Different units, different times. Techs have double-checked with calibrated probes. It's not the hardware.

text: This is a safety concern if over-temp alarms aren't firing. Are those affected too?

text: Not sure yet. The alarm thresholds haven't triggered on any of these units, but they're not near the limit anyway.

text: Are we logging the raw sensor values anywhere? I want to compare what the device sends vs what the dashboard shows.

text: Logs just show the same numbers as the dashboard. So the discrepancy is between device and probe, not app and backend.


domain: edtech

problem_statement: gradeSubmission() compares the score with strict greater-than against the pass mark, so a student scoring exactly the published threshold is graded as a fail. Every cohort loses the boundary band, and the error is invisible in aggregate pass-rate reporting. Fixed by using an inclusive comparison.

buggy_source:
// Enterprise Component: SysShield | Ticket: TICKET-5109 | Trace: INC-137
function gradeSubmission(score, passMark) {
            // BUG: strict greater-than excludes the boundary, so a student who
            // scores exactly the pass mark is recorded as a fail.
            if (score > passMark) {
                return { passed: true, band: 'pass' };
            }
            return { passed: false, band: 'fail' };
        }
        module.exports = { gradeSubmission };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for SysShield (TICKET-5109)
const assert = require('assert');
        const { gradeSubmission } = require('../src/handler');
        describe('PASS_MARK_BOUNDARY_EXCLUSION', function() {
            const PASS_MARK = 50;
            it('should pass a submission scoring exactly the pass mark', function() {
                const r = gradeSubmission(PASS_MARK, PASS_MARK);
                assert.strictEqual(r.passed, true);
            });
            it('should fail a submission one point below the pass mark', function() {
                const r = gradeSubmission(PASS_MARK - 1, PASS_MARK);
                assert.strictEqual(r.passed, false);
            });
            it('should pass a submission above the pass mark', function() {
                const r = gradeSubmission(PASS_MARK + 10, PASS_MARK);
                assert.strictEqual(r.passed, true);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,8 +1,7 @@
 // Enterprise Component: SysShield | Ticket: TICKET-5109 | Trace: INC-137
 function gradeSubmission(score, passMark) {
-            // BUG: strict greater-than excludes the boundary, so a student who
-            // scores exactly the pass mark is recorded as a fail.
-            if (score > passMark) {
+            // FIX: the pass mark itself is a passing score.
+            if (score >= passMark) {
                 return { passed: true, band: 'pass' };
             }
             return { passed: false, band: 'fail' };

reference_solution:
// Enterprise Component: SysShield | Ticket: TICKET-5109 | Trace: INC-137
function gradeSubmission(score, passMark) {
            // FIX: the pass mark itself is a passing score.
            if (score >= passMark) {
                return { passed: true, band: 'pass' };
            }
            return { passed: false, band: 'fail' };
        }
        module.exports = { gradeSubmission };

[User] Registrar

text: Just had a student come to me — transcript says Fail, but they scored exactly the pass mark. Is this just one case?

text: No, we've had at least five tickets just this morning. Same story: 'I passed, my transcript says failed.'

text: How widespread? Is it one course or all?

text: I checked the last two cohorts. Every student at the pass mark shows Fail on their transcript.

text: So a 70 shows as fail and a 71 shows as pass? That's what one student told me.

text: Yes. The gradebook has the correct result, but the transcript disagrees. Consistently.

text: OK, that's a serious issue. These students can't apply to jobs or further study with a fail on their record.

text: We're running manual transcript reviews for anyone who appeals. But we don't know who else is affected unless they notice.

text: Can you send me the course details and some student IDs? I'll investigate.

text: I've forwarded the list. The pattern is exact: score equals threshold, transcript says fail. No exceptions.

text: I've been looking at the transcript generation service. The pass mark in the database looks correct for these courses. My first guess is that the transcript is pulling grades from a different table, so I'm tracing the data flow.

text: Please keep us posted. We need to decide whether to send a campus-wide email or handle these quietly with appeals.


domain: fintech

problem_statement: calculateTotal() uses Number multiplication (dispatch service), which overflows for values above Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). When processing large USD amounts, the product silently loses precision. Fixed by using BigInt arithmetic.

buggy_source:
// Enterprise Component: PrimeStore | Ticket: TICKET-5155 | Trace: INC-131
function calculateTotal(unitPrice, quantity) {
    // BUG: Number multiplication can overflow for large money values
    // Example: 9999999999 * 9999999999 overflows Number.MAX_SAFE_INTEGER
    return unitPrice * quantity;
}
module.exports = { calculateTotal };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for PrimeStore (TICKET-5155)
const assert = require('assert');
const { calculateTotal } = require('../src/handler');

describe('PAYMENT_AMOUNT_OVERFLOW Fix Test', function() {
    it('should handle large payment amounts without overflow', function() {
        const result = calculateTotal(9999999999, 9999999999);
        // Number.MAX_SAFE_INTEGER = 9007199254740991
        // BigInt result = 99999999980000000001n — overflows with Number
        const expected = BigInt(9999999999) * BigInt(9999999999);
        assert.strictEqual(result, expected);
    });

    it('should handle normal amounts correctly', function() {
        const result = calculateTotal(100, 5);
        assert.strictEqual(result, 500n);
    });
});

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,7 +1,7 @@
 // Enterprise Component: PrimeStore | Ticket: TICKET-5155 | Trace: INC-131
 function calculateTotal(unitPrice, quantity) {
-    // BUG: Number multiplication can overflow for large money values
-    // Example: 9999999999 * 9999999999 overflows Number.MAX_SAFE_INTEGER
-    return unitPrice * quantity;
+    // FIX: Use BigInt for large money calculations to prevent overflow
+    const total = BigInt(unitPrice) * BigInt(quantity);
+    return total;
 }
 module.exports = { calculateTotal };

reference_solution:
// Enterprise Component: PrimeStore | Ticket: TICKET-5155 | Trace: INC-131
function calculateTotal(unitPrice, quantity) {
    // FIX: Use BigInt for large money calculations to prevent overflow
    const total = BigInt(unitPrice) * BigInt(quantity);
    return total;
}
module.exports = { calculateTotal };

text: Daily settlement total is off from ledger again. Only for a handful of large payments, but the amounts don't match what we expect.

text: Which payments? Are these the ones above the normal threshold?

text: Yes, all high-value. The ledger shows the correct gross, but the settlement total we're sending to the bank is slightly different.

text: Is this blocking the payout run? Need to know if we should hold.

text: We paused the run until we confirm. Bank hasn't received the file yet.

text: We need to quantify exposure. How many transactions, and total delta?

text: Six payments. Combined delta is under a hundred dollars, but each one is off in a different direction.

text: Different directions? That's odd. Usually if it's a cutoff issue it's consistently one way.

text: Is there a pattern with currencies? Mixing FX rates could cause small variances.

text: All USD. And it's not a timing thing — the ledger entries are posted, and the settlement total just doesn't add up.

text: Just saw the alert. Recap? What are we comparing against?

text: Settlement total from our dispatch service vs ledger postings. Only large USD payments are off.

text: We ruled out FX and timing because all same currency and ledger is final.

text: I'm going to pull the actual inputs for those six payments and run the same math locally to see where it diverges.

text: Back in 10. Taking the payout file generation down meanwhile.

text: Reproduced. If I take the payment amount and quantity from the dispatch payload and compute the total the way the service does, I get the wrong result. The ledger uses a different method and is right.


domain: devops

problem_statement: checkCertExpiry() in ledger uses >= instead of >, so a certificate whose validity window ends exactly at the current instant is still reported valid and the expiry passes silently. Fixed by requiring validTo strictly greater than now.

buggy_source:
// Enterprise Component: InfraVault | Ticket: TICKET-7677 | Trace: INC-784
function checkCertExpiry(sslCert_84, now) {
            const t = (typeof now === 'number') ? now : Date.now();
            if (sslCert_84.validTo >= t)
                return { valid: true, expiresIn: sslCert_84.validTo - t };
            return { valid: false, reason: 'Certificate expired' };
        }
        module.exports = { checkCertExpiry };

test_source:
// Test shim
if (typeof describe === 'undefined') {
    global.describe = function (name, fn) { fn(); };
    global.it = function (name, fn) { fn(); };
}
// Automated Test Suite for InfraVault (TICKET-7677)
const assert = require('assert');
        const { checkCertExpiry } = require('../src/handler');
        describe('CERT_EXPIRY', function() {
            // A fixed clock is injected so the boundary case is deterministic;
            // reading Date.now() twice made this test race against itself.
            const NOW = 1750000000000;
            it('should reject sslCert_84 whose validity ends exactly now', function() {
                const r = checkCertExpiry({ validTo: NOW }, NOW);
                assert.strictEqual(r.valid, false);
            });
            it('should accept valid sslCert_84', function() {
                const r = checkCertExpiry({ validTo: NOW + 86400000 }, NOW);
                assert.strictEqual(r.valid, true);
            });
        });

patch:
diff --git a/src/handler.js b/src/handler.js
--- a/src/handler.js
+++ b/src/handler.js
@@ -1,7 +1,7 @@
 // Enterprise Component: InfraVault | Ticket: TICKET-7677 | Trace: INC-784
 function checkCertExpiry(sslCert_84, now) {
             const t = (typeof now === 'number') ? now : Date.now();
-            if (sslCert_84.validTo >= t)
+            if (sslCert_84.validTo > t)
                 return { valid: true, expiresIn: sslCert_84.validTo - t };
             return { valid: false, reason: 'Certificate expired' };
         }

reference_solution:
// Enterprise Component: InfraVault | Ticket: TICKET-7677 | Trace: INC-784
function checkCertExpiry(sslCert_84, now) {
            const t = (typeof now === 'number') ? now : Date.now();
            if (sslCert_84.validTo > t)
                return { valid: true, expiresIn: sslCert_84.validTo - t };
            return { valid: false, reason: 'Certificate expired' };
        }
        module.exports = { checkCertExpiry };

text: Missed page on the payment-settlement service last night. It was supposed to stop serving at 02:00 and page us. It didn't. We killed it at 02:45.

text: Did customers see any issues during that time?

text: No. Requests kept succeeding the whole time. That's actually the annoying part — nothing looked wrong externally.

text: So the system kept working after it was supposed to be out of service. What does the runbook say about 02:00?

text: Runbook says at 02:00 it should raise a critical alert, stop taking traffic, and page the on-call. None of that happened.

text: We need to know what was served in that window. If it served after allowed hours, we might have to disclose.

text: All the logs show normal traffic. No errors, no rejects. It just refused to acknowledge that the window had closed.

text: So the only problem is that the automated alert didn't fire. The service itself was fine.

text: Right. And the status page kept saying 'all systems operational' until we manually updated it at 02:45.

text: I'm going to look into why the page never went out. Back in 10.

text: Found something. The alert definition is correct: it's supposed to trigger at 02:00. The evaluation log shows it ran at exactly 02:00:00 and the result was 'valid'.

text: How can it be valid at 02:00:00? The window was supposed to be over.

text: Could the evaluation be using a different timezone? If the rule runs in UTC but the window end was local, that would shift the result.

text: No, that was my first guess too. The timestamps all line up. The window end is 02:00:00 UTC and the evaluation ran at 02:00:00 UTC.


domain: healthcare

problem_statement: Dispatch position lookup falls back to an arbitrary cached fix from the shared telemetry map when the requested ambulance unit has no recent GPS report, returning another vehicle's coordinates to the wrong dispatch sphere and omitting any staleness evaluation against the maximum fix age window.

buggy_source:
// svc-ambulance-gps-stale-data — clinical service module
// build world_sample

const _positionCache = {};

function reportPosition(unitId, lat, lon, timestampMs) {
    _positionCache[unitId] = { lat, lon, timestampMs };
    return true;
}

function getDispatchPosition(unitId, nowMs) {
    const hit = _positionCache[unitId];
    if (hit) return { unitId, lat: hit.lat, lon: hit.lon, stale: false };
    const anyKey = Object.keys(_positionCache)[0];
    if (anyKey) {
        const other = _positionCache[anyKey];
        return { unitId, lat: other.lat, lon: other.lon, stale: false };
    }
    return null;
}

module.exports = { reportPosition, getDispatchPosition, MAX_FIX_AGE_MS: 90000 };

test_source:
const assert = require('assert');

const { reportPosition, getDispatchPosition } = require('../src/serviceHandler');

reportPosition('MEDIC-345', 40.6782, -73.9442, 1000);

// A unit with no fix of its own must never receive another unit's coordinates.
const foreign = getDispatchPosition('MEDIC-978', 1200);
assert.strictEqual(foreign, null,
    'unit with no GPS fix received another ambulance position (CWE-668)');

// A fix older than the max age must be reported stale, not as live position.
reportPosition('MEDIC-978', 40.7002, -73.9200, 1000);
const stale = getDispatchPosition('MEDIC-978', 1000 + 90000 + 1);
assert.strictEqual(stale.stale, true, 'expired GPS fix reported as live');
assert.strictEqual(stale.lat, null, 'stale fix still exposed coordinates');

const fresh = getDispatchPosition('MEDIC-345', 1100);
assert.strictEqual(fresh.stale, false);
assert.strictEqual(fresh.lat, 40.6782);
console.log('ok ambulance dispatch position scoping');

const _mod = require('../src/serviceHandler');
assert(typeof _mod === 'object' && Object.keys(_mod).length > 0,
    'service module exported nothing');

patch:
diff --git a/src/serviceHandler.js b/src/serviceHandler.js
index 9a6f1c8..e89d6b9 100644
--- a/src/serviceHandler.js
+++ b/src/serviceHandler.js
@@ -1,7 +1,8 @@
-// svc-ambulance-gps-stale-data — clinical service module
-// build world_sample
+// svc-ambulance-gps-stale-data — AMBULANCE_GPS_STALE_DATA (CWE-668: Exposure of Resource to Wrong Sphere in Dispatch Tracking)
+// world=world_sample

 const _positionCache = {};
+const MAX_FIX_AGE_MS = 90000;

 function reportPosition(unitId, lat, lon, timestampMs) {
     _positionCache[unitId] = { lat, lon, timestampMs };
@@ -10,13 +11,11 @@ function reportPosition(unitId, lat, lon, timestampMs) {

 function getDispatchPosition(unitId, nowMs) {
     const hit = _positionCache[unitId];
-    if (hit) return { unitId, lat: hit.lat, lon: hit.lon, stale: false };
-    const anyKey = Object.keys(_positionCache)[0];
-    if (anyKey) {
-        const other = _positionCache[anyKey];
-        return { unitId, lat: other.lat, lon: other.lon, stale: false };
+    if (!hit) return null;
+    if (nowMs - hit.timestampMs > MAX_FIX_AGE_MS) {
+        return { unitId, lat: null, lon: null, stale: true };
     }
-    return null;
+    return { unitId, lat: hit.lat, lon: hit.lon, stale: false };
 }

-module.exports = { reportPosition, getDispatchPosition, MAX_FIX_AGE_MS: 90000 };
\ No newline at end of file
+module.exports = { reportPosition, getDispatchPosition, MAX_FIX_AGE_MS };

reference_solution:
// svc-ambulance-gps-stale-data — AMBULANCE_GPS_STALE_DATA (CWE-668: Exposure of Resource to Wrong Sphere in Dispatch Tracking)
// world=world_sample

const _positionCache = {};
const MAX_FIX_AGE_MS = 90000;

function reportPosition(unitId, lat, lon, timestampMs) {
    _positionCache[unitId] = { lat, lon, timestampMs };
    return true;
}

function getDispatchPosition(unitId, nowMs) {
    const hit = _positionCache[unitId];
    if (!hit) return null;
    if (nowMs - hit.timestampMs > MAX_FIX_AGE_MS) {
        return { unitId, lat: null, lon: null, stale: true };
    }
    return { unitId, lat: hit.lat, lon: hit.lon, stale: false };
}

module.exports = { reportPosition, getDispatchPosition, MAX_FIX_AGE_MS };

test_command: node tests/bug.test.js

text: Weird. Unit 7 is showing at 5th and Oak on my screen, but the crew just radioed they cleared that call 20 minutes ago and are en route to St. Mary's.

text: That's a big discrepancy. We're expecting a STEMI patient.

text: If dispatch loses track of the rig, we can't prep the cath lab properly. Was the radio transmission clear?

text: Crystal clear. They said 'left scene, heading to your ER, ETA 15.' That was 20 minutes ago.

text: So where does the system think they are? Still at the scene?

text: Yes, shows them exactly at the scene location. Not moving.

text: Could the crew have forgotten to mark themselves en route on the console?

text: I asked – they did press 'En Route' when they left. The CAD shows the status as en route, but the map dot is still at the old spot.

text: We need a workaround. Can you give me a manual ETA based on the crew's call?

text: Yes, I'll use the radio ETA and flag the map position as stale. Meanwhile, can someone look into why the map didn't update?

text: Just joined – saw the thread. What are we seeing exactly? The unit status says en route but the map position stays at the previous scene?

text: Correct. And the dot hasn't moved for at least 20 minutes, but crew says they're on the highway.

text: Could be a GPS blackout zone, but the highway is pretty open. Let me pull the raw telemetry for that unit.

text: While you do that, we're using the radio ETA. But this is the second time this month. We need a fix.

text: I pulled the telemetry stream. That unit is reporting GPS every 10 seconds, no gaps. So the vehicle data is fine.