source: docs/P7-AdvancedDatabaseDevelopment/AdvancedDatabaseDevelopmentAIUsage.md@ 0cee8ec

main
Last change on this file since 0cee8ec was ef1c1c7, checked in by Stefan <trsunovstefan@…>, 6 days ago

Wiki docs, phase 6 and phase 7 added

  • Property mode set to 100644
File size: 10.1 KB
Line 
1# Advanced Database Development AI Usage
2
3## Name of AI service/solution that was used
4
5**Claude Code** (Anthropic)
6
7- **URL:** https://claude.com/claude-code
8- **Type of service/subscription:** Claude subscription, model Claude Opus 5.5.
9
10## Final result
11
12### Diagram
13
14No new diagram. The data model gains four columns and one table, all listed under "Changes to
15earlier phases" in [AdvancedDatabaseDevelopment](AdvancedDatabaseDevelopment.md):
16
17- `users.reserved_balance`;
18- `orders.filled_quantity` (with the status `partially_filled`);
19- `market_trades.buy_order_id` and `market_trades.sell_order_id`;
20- `order_events`.
21
22The optional link from a trade to the orders it filled is a new relationship, which
23[ERModel](../P1-ConceptualModel/ERModel.md) and
24[RelationalDesign](../P2-RelationalDesign/RelationalDesign.md) must show as well.
25
26### Results in details / description
27
28My requirements, given to the AI as a list:
29
30- complex order consistency: no invalid state changes, filled and remaining quantities
31 consistent, finished orders never processed again;
32- balance and order consistency: active orders consistent with reserved money and assets, no
33 inconsistent balance states from order operations;
34- trade consistency: trades only between valid compatible orders, never more than the remaining
35 quantity, orders, trades and balances kept consistent;
36- which kinds of triggers, procedures, functions and views to build;
37- a background job only if it is genuinely relevant;
38- basic column constraints kept out of P7.
39
40The AI:
41
42- Checked the existing schema against those requirements. It found that three of them could not
43 be expressed without small additions: there was no filled quantity, no place for reserved
44 cash, and no link from a trade to its orders. It added only the four columns listed above and
45 the event table.
46- For every feature, wrote down the business rule, why it is non-trivial, which PostgreSQL
47 feature implements it and which tables it affects. This is the structure I asked for, and
48 [AdvancedDatabaseDevelopment](AdvancedDatabaseDevelopment.md) follows it.
49- Implemented [`advanced_db.sql`](../../server/db/advanced_db.sql):
50 - 5 row triggers (order lifecycle, order events, trade validation, trade fill, trade
51 immutability);
52 - 3 deferred constraint triggers (reserved cash, reserved crypto, cash equals ledger);
53 - the functions `place_order`, `match_order`, `execute_trade`, `cancel_order`,
54 `order_reservation` and `latest_price`;
55 - 4 views;
56 - the background job `fill_marketable_orders`.
57- Checked the faculty server before choosing how to schedule the background job. There is no
58 `pg_cron` and the role is not a superuser, so the job is a function that the bot process calls
59 after every round of price ticks.
60- Adapted the two data scripts to the new consistency rules and verified that both P6 report
61 outputs stay exactly as documented.
62- Wrote [`advanced_db_tests.sql`](../../server/db/advanced_db_tests.sql): a trading story with 41
63 checks, rolled back at the end. It ran them until all passed. The one failure along the way was
64 in the test itself: a check read the data in the same statement as the job it was checking.
65- Wired the prototype to use the new functions:
66 - order placement is a single `place_order` call, with market or limit orders;
67 - the order book, open orders and cancel are available from the menu, with cancel picked from
68 a numbered list;
69 - the balance screen shows reserved cash;
70 - the bot runs the job.
71
72 All of this was verified through the CLI and with the bot running.
73- Wrote this documentation.
74
75## Summary of AI involvement
76
77| | This session — 2026-09-24 |
78|---|---|
79| **What I brought** | The P7 requirements for EduBerza: order, balance and trade consistency, the kinds of triggers, procedures and views, and the condition on the background job |
80| **What the AI did** | Turned the requirements into concrete rules on the existing schema, implemented and tested them, wired them into the prototype, wrote the documentation |
81| **What I decided** | The requirements themselves; to discard the AI's earlier, self-proposed P7 version (see the log) and redo the phase from my requirements; to keep the schema changes minimal |
82
83## Entire AI usage log
84
85### 2026-09-24 — earlier attempt, discarded
86
87Earlier in the same session I had pasted the P7 and P8 rubrics without ideas of my own, and the
88AI proposed and implemented a P7 of its own design: custom domains, an append-only ledger,
89candles derived from trades and a maintenance job. Before submitting anything I decided to redo
90the phase from my own requirements, and asked for that version to be reverted. None of it
91remains in the project. It is mentioned here only so the log is complete.
92
93### 2026-09-24 — this phase
94
95**Prompt (student, verbatim):**
96> P7 requirements are:
97>
98> more complex data constraints and consistency requirements
99> business scenarios that require special database checks
100> triggers
101> stored procedures and functions
102> views
103> background jobs
104> documentation of the implementation
105>
106> Basic column constraints such as NOT NULL, UNIQUE, CHECK, PRIMARY KEY, and basic foreign keys
107> are Phase P2 and must NOT be proposed as P7 features.
108>
109> Based on my existing EduBerza database, identify and implement only genuinely NON-TRIVIAL P7
110> requirements.
111>
112> Focus on these types of requirements:
113>
114> Complex order consistency
115> Prevent invalid order state changes.
116> Ensure filled/remaining quantities stay consistent.
117> Prevent cancelled or completed orders from being processed again.
118> Balance and order consistency
119> Ensure active orders are consistent with reserved virtual money/assets.
120> Prevent inconsistent balance states caused by order operations.
121> Trade consistency
122> Ensure a trade can only happen between valid compatible orders.
123> Ensure trade quantity cannot exceed the remaining order quantity.
124> Keep orders, trades, and balances consistent.
125> Triggers
126> Create triggers only for automatic database behavior that is genuinely required, such as:
127> automatic validation of complex business rules
128> automatic order status changes
129> automatic recording of important order/trade events
130> Stored procedures/functions
131> Create procedures/functions for complex database operations such as:
132> placing an order with the necessary consistency checks
133> executing a trade while updating all related data consistently
134> Views
135> Create useful views for derived application data, such as:
136> current order book
137> active orders
138> trader portfolio/balances
139> order/trade history
140>
141> Do not recreate reports that were already implemented in P6 unless a view is needed
142> specifically as part of P7.
143>
144> Background jobs
145> Implement a meaningful background database job only if it is relevant to the existing
146> EduBerza design.
147> Do not create an artificial background job just to satisfy the requirement.
148>
149> For every proposed P7 feature, explain:
150>
151> the business rule
152> why it is non-trivial
153> which PostgreSQL feature should implement it
154> which existing tables it affects
155>
156> Then implement the selected P7 features in the existing project without redesigning the
157> database unnecessarily.
158>
159> Finally, document:
160>
161> complex data requirements
162> triggers
163> stored procedures/functions
164> views
165> background jobs
166> how each one maintains consistency or enforces a business rule
167> examples/tests proving that the rules work
168>
169> Keep the implementation strictly within P7.
170
171(The first time I sent it the message was interrupted; I sent it again, followed by "and revert
172the previous changes".)
173
174**Response (AI, summarised):**
175
176- **Revert.** It restored every file changed by the discarded attempt to the last commit and
177 deleted the files that attempt had created. It kept the SSH connection support (from before
178 P7) and my own uncommitted edits.
179- **Analysis.** It reported that three requirements need data the schema doesn't have — a filled
180 quantity, a reserved cash balance, and trade-to-order links — and added exactly those
181 (`orders.filled_quantity` plus status `partially_filled`, `users.reserved_balance`,
182 `market_trades.buy_order_id`/`sell_order_id`), plus `order_events` for the automatic event
183 recording.
184- **Design:**
185 - A trade is always a `market_trades` row naming the orders it fills. Triggers on that table
186 validate compatibility and fill the orders; the order's status is derived from its filled
187 quantity by the order trigger.
188 - `filled_quantity` may only change while a trade is being recorded, which is detected through
189 a transaction-local setting.
190 - The three balance rules are deferred constraint triggers, because every legitimate operation
191 breaks them between its statements.
192 - Placing an order reserves first, then matches against the order book (price–time priority),
193 then fills the marketable remainder from the simulated market.
194 - Rounding of reservations is defined once (`order_reservation`), so placing, filling,
195 cancelling and checking always agree.
196- **Background job.** It argued the job is relevant rather than artificial: the market price is
197 moved by the simulator, and without the job resting limit orders would never fill once the
198 price reaches them. It explained why a trigger on the bot's price ticks would be the wrong
199 place for this work.
200- **Verification** (local PostgreSQL 17 in Docker only, never the faculty database):
201 - both P6 reports return the documented numbers;
202 - the P6 demo script can be re-run without doubling anything;
203 - the test story passes 41 of 41;
204 - through the CLI: a limit sell resting in the book, a crossing limit buy trading at the resting
205 price with the difference refunded, a market buy filled partly from the book and partly from
206 the market, the order book, open orders, and cancelling with the reservation released;
207 - with the bot running, the job filled a resting limit order once the price walk reached it.
208- **Documentation.** It wrote [AdvancedDatabaseDevelopment](AdvancedDatabaseDevelopment.md) and
209 this log, with the SQL on the page taken automatically from `advanced_db.sql` so the two cannot
210 differ, together with the faculty-site (wiki) versions of both pages.
211
212**What I decided:** the requirements are mine. I kept the AI's minimal schema additions and its
213design for fulfilling them, and asked for no changes to it before it was implemented.
Note: See TracBrowser for help on using the repository browser.