From 4519fc59be6a91b7a84e5a19ea7cde54d2c502b3 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 13:44:37 -0700 Subject: [PATCH] P4-13: spike on real legacy outputs under GnuCOBOL The spike note, docs/spikes/p4-13-gnucobol.md, answers D12 of docs/pipeline-4.md: CardDemo's batch programs compiled and run under GnuCOBOL, and their outputs set against the reconciled rules. The harness that ran it is in docs/spikes/p4-13/. It is not product code, and the run's outputs are not committed. - 10 of the 12 batch programs compile under GnuCOBOL 3.1.2 (Debian's package, in a container) and 8 run to a normal end on CardDemo's own data, in the JCL's order. CBSTM03A reads z/OS control blocks and crashes. CBEXPORT and CBIMPORT do not compile as written: their RECORD KEY is a WORKING-STORAGE field. - What they needed: tabs expanded; -fsign=EBCDIC for the data's overpunch signs; stand-ins for CEE3ABD and COBDATFT (translated line for line); a driver for CBACT04C's JCL PARM; the VSAM files built from the ASCII data with the JCL's keys and the XREF alternate key; and a stand-in for DFSORT. - The reconciled rules for posting and interest agree with the real outputs: 300 of 300 reject decisions, every account and category balance after posting, and 50 of 50 interest amounts, but only when amounts are truncated to the cent, which the interest rule does not say. - One recommended rule is wrong. The interest batch never posts the last account's interest: its loop ends before the end-of-file branch runs. That is a defect in CardDemo, and the rule says the opposite. The plan's P4-13 row and D12 in docs/pipeline-4.md record the result, and the note proposes a story for an optional legacy run in the golden datasets. Prepared with AI assistance. --- docs/pipeline-4.md | 7 +++ docs/plan.md | 2 +- docs/spikes/p4-13-gnucobol.md | 98 +++++++++++++++++++++++++++++ docs/spikes/p4-13/Dockerfile | 5 ++ docs/spikes/p4-13/check.py | 113 +++++++++++++++++++++++++++++++++ docs/spikes/p4-13/make.py | 115 ++++++++++++++++++++++++++++++++++ docs/spikes/p4-13/rules.py | 9 +++ docs/spikes/p4-13/run.sh | 70 +++++++++++++++++++++ docs/spikes/p4-13/sort.py | 10 +++ 9 files changed, 428 insertions(+), 1 deletion(-) create mode 100644 docs/spikes/p4-13-gnucobol.md create mode 100644 docs/spikes/p4-13/Dockerfile create mode 100644 docs/spikes/p4-13/check.py create mode 100644 docs/spikes/p4-13/make.py create mode 100644 docs/spikes/p4-13/rules.py create mode 100644 docs/spikes/p4-13/run.sh create mode 100644 docs/spikes/p4-13/sort.py diff --git a/docs/pipeline-4.md b/docs/pipeline-4.md index d9a9400d..93912216 100644 --- a/docs/pipeline-4.md +++ b/docs/pipeline-4.md @@ -286,6 +286,13 @@ Each capability already has a risk (P3-24) and touches a list of things (money, Whether real outputs can be captured from the legacy programs without a mainframe: the batch programs compiled and run under GnuCOBOL on the golden datasets' inputs, with the files they read built from the copybooks. CICS screens are out of reach this way. The spike records which CardDemo batch programs compile and run, what they need (files, sort, utilities), and whether their outputs can replace the rules' expected outputs in D10. +**Result** (28 November 2026, [spikes/p4-13-gnucobol.md](spikes/p4-13-gnucobol.md)): +- 10 of the 12 batch programs compile and 8 run. The statements program reads z/OS control blocks, and the export and import programs do not compile as written. +- The posting and interest rules agree with the real outputs, at the program's precision (it truncates to the cent). +- One recommended rule is wrong: the last account's interest is never posted. + +So real outputs can replace the rules' expected outputs for batch programs that run, and a difference sends the rule back to the reconciliation. + ## 5. Design context Read from the context folder, by name: diff --git a/docs/plan.md b/docs/plan.md index 5ac79bb6..eb011298 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -177,7 +177,7 @@ Agreed by the owner on 24 November 2026. From the reconciled and reviewed result | P4-10 | Live acceptance and README | [§8](pipeline-4.md) | Done 26 November 2026 ([results](pipeline-4.md)): rounds 1 and 2 on CardDemo from the CLI; round 2's persona, design system and *Needs change* redid only what they reach, and a kept part now records its pieces so a later round can say why. On CardDemo, from the CLI: the prototype covers every screen, a second round with added context changes only what it should, and the README and `docs/cli.md` describe pipeline 4 from the tested commands | | P4-11 | Golden datasets and equivalence tests | [§4 D10](pipeline-4.md) | #421 · Done 26 November 2026 (#456; the owner moved it forward from Later, the same day), with no model: per capability, a golden dataset from the worked examples and decision tables in each form of the package, with `golden/compare.py` setting formatting apart from business differences, and the test-generation task naming every case. On CardDemo: 1,595 cases for 139 capabilities, 746 edge cases and 82 combinations left for the owner. Expected outputs come from the rules until P4-13 | | P4-12 | Risk and replacement order | [§4 D11](pipeline-4.md) | **Later** (the owner, 26 November 2026). Capabilities are ordered for replacement from their risk and what they touch, low-risk and read-only first and money, security and adjudication last, shared data and screens kept together; the order and its reasons are on the design page and in the package's constitution and tasks | -| P4-13 | Spike: real legacy outputs under GnuCOBOL (low priority) | [§4 D12](pipeline-4.md) | **Later** (the owner, 26 November 2026). A note records which CardDemo batch programs compile and run under GnuCOBOL with files built from the copybooks, and whether their outputs can replace the rules' expected outputs in the golden datasets | +| P4-13 | Spike: real legacy outputs under GnuCOBOL (low priority) | [§4 D12](pipeline-4.md) | #423 · Spike written 28 November 2026 ([spikes/p4-13-gnucobol.md](spikes/p4-13-gnucobol.md)), for the owner: 10 of CardDemo's 12 batch programs compile under GnuCOBOL 3.1.2 in a container and 8 run to a normal end on CardDemo's own data. The reconciled rules for posting and interest agree with the real outputs (300 of 300 reject decisions, 50 of 50 interest amounts), but only when amounts are truncated to the cent, which the interest rule does not say. The real run also shows that one recommended rule is wrong: the interest batch never posts the last account's interest, a CardDemo defect. Proposed: a story for an optional legacy run in the golden datasets | ## Release 1.0: anyone can try it diff --git a/docs/spikes/p4-13-gnucobol.md b/docs/spikes/p4-13-gnucobol.md new file mode 100644 index 00000000..3573718a --- /dev/null +++ b/docs/spikes/p4-13-gnucobol.md @@ -0,0 +1,98 @@ +# Spike P4-13: real legacy outputs under GnuCOBOL + +Story P4-13 (#423), 28 November 2026. The question ([pipeline-4.md, section 4 D12](../pipeline-4.md)): can real outputs be captured from the legacy programs without a mainframe? The batch programs are compiled and run under GnuCOBOL, with the files they read built from the copybooks and the data. Which of CardDemo's batch programs compile and run, what do they need, and can their outputs replace the rules' expected outputs in the golden datasets (D10)? CICS screens are out of reach this way. + +The harness is in [p4-13/](p4-13/). It is not product code, and the run's outputs are not committed. + +## Answer + +**Yes, for the batch programs that run, and the real outputs found a rule the reconciliation got wrong.** + +- 10 of CardDemo's 12 batch programs compile under GnuCOBOL 3.1.2, and 8 run to a normal end on CardDemo's own data, in the order its JCL runs the nightly cycle. CBSTM03A, with its subprogram CBSTM03B, compiles but crashes; CBEXPORT and CBIMPORT do not compile as written. +- The reconciled rules for posting (CBTRN02C) and interest (CBACT04C), carried out as their text says, agree with the real programs: + - every one of the 300 reject decisions; + - every account and category balance after posting; + - every one of the 50 interest amounts. +- The exceptions are the findings: + 1. **The interest rule never says how to round.** The program truncates to the cent, like a COMPUTE without ROUNDED. Rounded half up, only 22 of the 50 amounts match. An expected output written from the rule's words ("balance times rate divided by 1200") could be wrong by a cent in more than half the cases. + 2. **A recommended rule is wrong.** "WHEN the end of the category balance file is reached, THE interest batch SHALL post the last account's accumulated interest to that account before closing its files" has medium confidence. The real run shows the opposite: the last account's interest transaction is written, but its balance and cycle totals are never updated. The loop ends before its end-of-file branch can run. The rule's possible defect (an empty file abends) is wrong for the same reason. This is a real CardDemo defect: plain COBOL control flow, the same on z/OS. + +So real outputs can replace the rules' expected outputs for batch programs that compile and run. More than that, they check the rules: a case whose real output differs from the rule's expected output is a rule to send back to the reconciliation, with the run as evidence. + +## Setup + +- **The compiler.** GnuCOBOL 3.1.2, Debian bookworm's `gnucobol3` package, in a container built from [p4-13/Dockerfile](p4-13/Dockerfile). Homebrew could not install it on this Mac (Intel, macOS 26): it builds from source, and its `autoreconf` step fails for GnuCOBOL and for GMP alike. The indexed-file handler is Berkeley DB. +- **Compile options:** + - `-std=ibm -fixed`; + - `-fsign=EBCDIC`, because CardDemo's ASCII data keeps the mainframe's trailing overpunch signs (`{` for +0, `G` for +7); + - the copybooks on the include path. +- **The source,** with tab characters expanded (width 4) and nothing else changed. Some copybooks, `CUSTREC.CPY` among them, carry tabs that push the PICTURE clauses past column 72. +- **What is not COBOL,** replaced: + - `CEE3ABD`, Language Environment's abend service: a stand-in that says so and ends with return code 16; + - `COBDATFT`, CardDemo's assembler date routine: translated line for line (84 lines of assembler, about 20 of COBOL); + - CBACT04C's `PARM='2022071800'` from INTCALC.jcl: a driver passes it as z/OS does, a halfword length and then the text; + - DFSORT in TRANREPT.jcl: [p4-13/sort.py](p4-13/sort.py), by card number, with the JCL's processed-date window. +- **The VSAM files:** + - each KSDS is built from CardDemo's `app/data/ASCII` files, with the keys and record sizes of the JCL's `DEFINE CLUSTER`; + - the cross-reference file is built with its alternate key on the account ID (the AIX CBACT04C opens); + - the results are read back with an unloader. + + [p4-13/make.py](p4-13/make.py) writes the loaders. +- **The cycle,** in [p4-13/run.sh](p4-13/run.sh): + 1. the four read programs; + 2. POSTTRAN (CBTRN02C); + 3. CBTRN01C; + 4. INTCALC (CBACT04C); + 5. TRANREPT (the sort, then CBTRN03C); + 6. CREASTMT (CBSTM03A). + +## Program by program + +| Program | Job | Compiles | Runs | What it needed | +|---|---|---|---|---| +| CBACT01C | READACCT | Yes | Yes, return code 0 | The COBDATFT stand-in | +| CBACT02C, CBACT03C, CBCUS01C | READCARD, READXREF, READCUST | Yes | Yes, return code 0 | Nothing | +| CBTRN01C | none (no JCL runs it) | Yes | Yes, return code 0 | The posted transaction file: it opens it for input (file status 35 before POSTTRAN) | +| CBTRN02C | POSTTRAN | Yes | Yes, return code 4: 300 read, 262 posted, 38 rejected (the program's code for "some rejected") | Nothing | +| CBACT04C | INTCALC | As a module | Yes, return code 0: 50 interest transactions | A driver for `PROCEDURE DIVISION USING` the JCL PARM | +| CBTRN03C | TRANREPT | Yes | Yes, return code 0: the daily report | The sort. With the JCL's fixed 2022 window it reports nothing, because CBTRN02C stamps transactions with the run's own date, as it would on z/OS today; run with that day as the window | +| CBSTM03A, CBSTM03B | CREASTMT | Yes (CBSTM03B as a module) | **No:** SIGSEGV | It walks z/OS control blocks (PSA, then TCB, then TIOT) through pointers to list the job's DD names. No Linux process has them | +| CBEXPORT, CBIMPORT | CBEXPORT, CBIMPORT | **No** | – | A fault in the source: the `RECORD KEY` names `EXPORT-SEQUENCE-NUM`, a field of WORKING-STORAGE (`COPY CVEXPORT`), not of the file's record. Not changed, since the spike runs the source as it is | + +## The rules against the real outputs + +[p4-13/check.py](p4-13/check.py) carries out the reconciled rules of the published CardDemo review ([reports/carddemo/reconciled](../../reports/carddemo/reconciled/index.html); 43 rules for CBTRN02C and CBACT04C, read by [p4-13/rules.py](p4-13/rules.py)) on the same input data, in Python and independently of the COBOL, and compares: + +| Check | Agreement | +|---|---| +| CBTRN02C's reject reason for each daily transaction (100 card unknown, 101 account unknown, 102 over the limit, 103 expired, in the rules' order; "a projection equal to the limit passes"; "both over the limit and expired: only 103") | 300 of 300 (38 rejected, all 102) | +| Each account's balance and cycle credit and debit after posting | 50 of 50 | +| Each category balance after posting, created where none existed | 100 of 100 | +| CBACT04C's interest amount for each category balance, the group's rate or else DEFAULT's, "balance times rate divided by 1200" | 50 of 50 truncated to the cent; 22 of 50 rounded half up | +| Each account after interest: the balance plus its interest, and the cycle totals reset | 49 of 50: the last account is not updated (finding 2) | +| CBTRN02C's return code, "4 when the reject count is greater than 0" | Yes | + +## What it means for the golden datasets (D10) + +- **For batch programs that compile and run,** a case's expected output can come from the real program. That needs: + - its input files built from the case's values with the copybooks' layouts; + - the program run in the container; + - its output files read back the same way. + + It is exact for money, dates and codes, which is what golden datasets compare. +- **Where the real output and the rule disagree,** the rule is the suspect, not the run. Finding 2 is that case. A case like it should be sent back to the reconciliation as evidence for the rule's unit, not kept as an expected output. +- **Rounding** must be stated. A golden dataset of money values needs the program's precision, which here is truncation. The rules' text needs to say it. +- **Out of reach this way:** + - CICS screens; + - programs that read z/OS control blocks (CBSTM03A); + - source that does not compile as written (CBEXPORT, CBIMPORT); + - anything that needs DB2, IMS or MQ, which CardDemo keeps in optional modules not tried here. + +## What it took + +About two hours, no cloud and no cost: the container, the harness, the run and the check. The container is Debian's official image with Debian's own package; nothing was installed on the Mac. + +## Proposed follow-ups + +- **A story:** in the design's golden datasets, an optional "legacy run" that does what this spike did for every batch case. Each case is marked as confirmed, or as different with both outputs. A difference becomes an SME question on the rule's unit in the next reconciliation round. +- **For the owner:** finding 2 is a defect in CardDemo itself. The reconciled rule should be corrected in the next round, and the rounding added to the interest rule. diff --git a/docs/spikes/p4-13/Dockerfile b/docs/spikes/p4-13/Dockerfile new file mode 100644 index 00000000..fbb4a45f --- /dev/null +++ b/docs/spikes/p4-13/Dockerfile @@ -0,0 +1,5 @@ +FROM debian:bookworm-slim +RUN apt-get -o Acquire::ForceIPv4=true -o Acquire::Retries=3 update \ + && apt-get -o Acquire::ForceIPv4=true -o Acquire::Retries=3 install -y --no-install-recommends gnucobol3 \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /work diff --git a/docs/spikes/p4-13/check.py b/docs/spikes/p4-13/check.py new file mode 100644 index 00000000..5a7386e4 --- /dev/null +++ b/docs/spikes/p4-13/check.py @@ -0,0 +1,113 @@ +"""P4-13: the reconciled rules for CBTRN02C (posting) and CBACT04C (interest), carried out as their text says, on CardDemo's +own data, compared with what the real programs wrote under GnuCOBOL. Usage: python3 -I check.py """ +import collections +import sys +from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal +from pathlib import Path + +W = Path(sys.argv[1]) +D, DATA = W / "run", W / "data" +OVER = {"{": (0, 1), "}": (0, -1), **{c: (i + 1, 1) for i, c in enumerate("ABCDEFGHI")}, **{c: (i + 1, -1) for i, c in enumerate("JKLMNOPQR")}} + + +def num(field: bytes, scale: int) -> Decimal: + """A zoned decimal with a trailing overpunch sign, as CardDemo's ASCII data has it.""" + s = field.decode("latin-1") + sign = 1 + if s and s[-1] in OVER: + digit, sign = OVER[s[-1]] + s = s[:-1] + str(digit) + return Decimal(int(s or 0) * sign).scaleb(-scale) + + +def records(path, size): + data = path.read_bytes() + return [data[i:i + size] for i in range(0, len(data), size)] + + +def account(r): + return {"id": r[0:11], "bal": num(r[12:24], 2), "limit": num(r[24:36], 2), "exp": r[58:68].decode(), "credit": num(r[78:90], 2), + "debit": num(r[90:102], 2), "group": r[112:122].decode().strip()} + + +def tran(r): + return {"id": r[0:16], "type": r[16:18], "cat": r[18:22], "amt": num(r[132:143], 2), "card": r[262:278], "orig": r[278:304].decode()[:10]} + + +xref = {r[0:16]: r[25:36] for r in records(DATA / "XREF.seq", 50)} +accounts = {a["id"]: a for a in map(account, records(DATA / "ACCT.seq", 300))} +tcat = {r[0:17]: num(r[17:28], 2) for r in records(DATA / "TCAT.seq", 50)} +daily = [tran(r) for r in records(DATA / "DALY.seq", 350)] + +# ---- CBTRN02C, as the rules say ---------------------------------------------------------------------------------------- +expected = {} +for t in daily: + reason = 0 + acct_id = xref.get(t["card"]) + if acct_id is None: + reason = 100 # "Reject unknown card number": 100, card not found + elif acct_id not in accounts: + reason = 101 # "Reject transaction for unknown account": 101 + else: + a = accounts[acct_id] + if a["limit"] < a["credit"] - a["debit"] + t["amt"]: + reason = 102 # over the limit; "a projection equal to the limit passes" + if a["exp"] < t["orig"]: + reason = 103 # expired; "both over the limit and expired: only 103" + expected[t["id"]] = reason + if reason == 0: # "Post transaction to account balances" and the category balance + a = accounts[acct_id] + a["bal"] += t["amt"] + if t["amt"] >= 0: + a["credit"] += t["amt"] + else: + a["debit"] += t["amt"] + key = acct_id + t["type"] + t["cat"] + tcat[key] = tcat.get(key, Decimal(0)) + t["amt"] + +actual = {r[0:16]: int(r[350:354]) for r in records(D / "DALYREJS.seq", 430)} +posted = {tran(r)["id"] for r in records(D / "TRAN.posted.seq", 350)} +for t in daily: + actual.setdefault(t["id"], 0 if t["id"] in posted else -1) +agree = sum(expected[k] == actual[k] for k in expected) +print(f"CBTRN02C: {len(daily)} daily transactions; reasons by the rules {dict(collections.Counter(expected.values()))}; " + f"by the program {dict(collections.Counter(actual.values()))}; the same for {agree} of {len(daily)}") +for k in expected: + if expected[k] != actual[k]: + print(" differs:", k.decode(), "rules", expected[k], "program", actual[k]) +after = {a["id"]: a for a in map(account, records(D / "ACCT.posted.seq", 300))} +same = sum(after[i]["bal"] == accounts[i]["bal"] and after[i]["credit"] == accounts[i]["credit"] and after[i]["debit"] == accounts[i]["debit"] for i in accounts) +print(f" accounts after posting: balance and cycle totals the same for {same} of {len(accounts)}") +posted_tcat = {r[0:17]: num(r[17:28], 2) for r in records(D / "TCAT.posted.seq", 50)} +print(f" category balances after posting: {sum(posted_tcat.get(k) == v for k, v in tcat.items())} of {len(tcat)} the same " + f"({len(posted_tcat)} in the program's file)") + +# ---- CBACT04C, as the rules say ---------------------------------------------------------------------------------------- +rates = {r[0:16].decode(): num(r[16:22], 2) for r in records(DATA / "DISC.seq", 50)} +interest = collections.defaultdict(Decimal) +lines = [] +for key in sorted(posted_tcat): + acct_id, ttype, cat = key[0:11], key[11:13].decode(), key[13:17].decode() + group = after[acct_id]["group"] if acct_id in after else "" + rate = rates.get(f"{group:10}{ttype}{cat}", rates.get(f"{'DEFAULT':10}{ttype}{cat}", Decimal(0))) # the group's rate, else DEFAULT + if rate != 0: + raw = posted_tcat[key] * rate / 1200 # "balance times rate divided by 1200" + lines.append((acct_id, raw)) + interest[acct_id] += raw +written = [num(r[132:143], 2) for r in records(D / "SYSTRAN.seq", 350)] +for mode, how in (("truncated", ROUND_DOWN), ("rounded", ROUND_HALF_UP)): + mine = [raw.quantize(Decimal("0.01"), how) for _, raw in lines] + print(f"CBACT04C: {len(written)} interest transactions written; by the rules {len(mine)}; amounts the same, {mode} to the cent: " + f"{sum(a == b for a, b in zip(mine, written))} of {len(written)}") +final = {a["id"]: a for a in map(account, records(D / "ACCT.interest.seq", 300))} +ok = 0 +for i, a in final.items(): + total = sum(raw.quantize(Decimal("0.01"), ROUND_DOWN) for acct, raw in lines if acct == i) + ok += a["bal"] == after[i]["bal"] + total and (i not in interest or (a["credit"] == 0 and a["debit"] == 0)) +print(f" accounts after interest: balance plus the account's interest, and the cycle totals reset where interest posted: {ok} of {len(final)}") + +for i, a in final.items(): + total = sum(raw.quantize(Decimal("0.01"), ROUND_DOWN) for acct, raw in lines if acct == i) + if not (a["bal"] == after[i]["bal"] + total and (i not in interest or (a["credit"] == 0 and a["debit"] == 0))): + print(" differs:", i.decode(), "before", after[i]["bal"], after[i]["credit"], after[i]["debit"], "interest lines", + [str(r) for acct, r in lines if acct == i], "program", a["bal"], a["credit"], a["debit"]) diff --git a/docs/spikes/p4-13/make.py b/docs/spikes/p4-13/make.py new file mode 100644 index 00000000..20fb765e --- /dev/null +++ b/docs/spikes/p4-13/make.py @@ -0,0 +1,115 @@ +"""P4-13 spike harness: prepares CardDemo's batch cycle to compile and run under GnuCOBOL in a container. + +Writes into /work: + src/ CardDemo's cbl and cpy with tab characters expanded (width 4); nothing else is changed + stubs/ stand-ins for what is not COBOL: CEE3ABD (the LE abend service), COBDATFT (CardDemo's assembler date routine, + translated line for line), RUN04C (passes CBACT04C the JCL PARM as z/OS does: a halfword length, then the text) + util/ LOADKSDS-: a fixed-length sequential file -> an indexed file (the IDCAMS REPRO of the JCL); + DUMPKSDS-: an indexed file -> a fixed-length sequential file, to read the results + data/ the ASCII data files as fixed-length records with no line ends +Usage: python3 -I make.py +""" +import pathlib +import shutil +import sys + +repo, out = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]) +work = out / "work" +if work.exists(): + shutil.rmtree(work) +for sub in ("src/cbl", "src/cpy", "stubs", "util", "data"): + (work / sub).mkdir(parents=True) + +for kind in ("cbl", "cpy"): + for f in (repo / "app" / kind).iterdir(): + if f.is_file(): + text = f.read_bytes().decode("latin-1") + (work / "src" / kind / f.name).write_bytes("\n".join(line.expandtabs(4) for line in text.splitlines()).encode("latin-1") + b"\n") + +# name, data file, record length, key length (the JCL's DEFINE CLUSTER: KEYS(n 0) RECORDSIZE(r r)) +KSDS = [("ACCT", "acctdata.txt", 300, 11), ("CARD", "carddata.txt", 150, 16), ("XREF", "cardxref.txt", 50, 16), ("CUST", "custdata.txt", 500, 9), + ("DISC", "discgrp.txt", 50, 16), ("TCAT", "tcatbal.txt", 50, 17), ("TCTG", "trancatg.txt", 60, 6), ("TTYP", "trantype.txt", 60, 2), + ("TRAN", None, 350, 16)] +ALT = {"XREF": (25, 11)} # CBACT04C's ALTERNATE RECORD KEY FD-XREF-ACCT-ID (the AIX of the JCL): offset, length +SEQ = [("DALY", "dailytran.txt", 350)] + + +def fixed(name, size): + """A data file as fixed-length records: each line padded to the record length, no line ends.""" + lines = (repo / "app/data/ASCII" / name).read_bytes().decode("latin-1").splitlines() + return b"".join(line.ljust(size)[:size].encode("latin-1") for line in lines if line) + + +def fields(side, name, size, key): + if name not in ALT: + return [f" 05 FILLER PIC X({size - key})."] + at, n = ALT[name] + return [f" 05 FILLER PIC X({at - key}).", f" 05 {side}-ALT PIC X({n}).", f" 05 FILLER PIC X({size - at - n})."] + + +def alt(side, name): + return [f" ALTERNATE RECORD KEY IS {side}-ALT"] if name in ALT else [] + + +def cobol(lines): + long = [x for x in lines if len(x) > 65 and not x.startswith("*")] + assert not long, long # fixed format: code ends at column 72 + return "\n".join((" " + x) if not x.startswith("*") else (" " + x) for x in lines) + "\n" + + +for name, data, size, key in KSDS: + if data: + (work / "data" / f"{name}.seq").write_bytes(fixed(data, size)) + for verb in ("LOAD", "DUMP"): + prog = f"{verb}{name}" + src, dst = ("IN-F", "OUT-F") if verb == "LOAD" else ("IN-F", "OUT-F") + indexed_in = verb == "DUMP" + (work / "util" / f"{prog}.cbl").write_text(cobol([ + "IDENTIFICATION DIVISION.", f"PROGRAM-ID. {prog}.", "ENVIRONMENT DIVISION.", "INPUT-OUTPUT SECTION.", "FILE-CONTROL.", + " SELECT IN-F ASSIGN TO INFILE", + *([" ORGANIZATION IS INDEXED", " ACCESS MODE IS SEQUENTIAL", " RECORD KEY IS IN-KEY"] + alt("IN", name) + if indexed_in else [" ORGANIZATION IS SEQUENTIAL"]), + " FILE STATUS IS IN-ST.", + " SELECT OUT-F ASSIGN TO OUTFILE", + *([" ORGANIZATION IS SEQUENTIAL"] if indexed_in else + [" ORGANIZATION IS INDEXED", " ACCESS MODE IS SEQUENTIAL", " RECORD KEY IS OUT-KEY"] + alt("OUT", name)), + " FILE STATUS IS OUT-ST.", + "DATA DIVISION.", "FILE SECTION.", + "FD IN-F.", "01 IN-R.", f" 05 IN-KEY PIC X({key}).", *fields("IN", name, size, key), + "FD OUT-F.", "01 OUT-R.", f" 05 OUT-KEY PIC X({key}).", *fields("OUT", name, size, key), + "WORKING-STORAGE SECTION.", "01 IN-ST PIC XX.", "01 OUT-ST PIC XX.", "01 N PIC 9(7) VALUE 0.", + "PROCEDURE DIVISION.", " OPEN INPUT IN-F OUTPUT OUT-F.", + " PERFORM UNTIL IN-ST NOT = '00'", " READ IN-F", " IF IN-ST = '00'", " MOVE IN-R TO OUT-R", + " WRITE OUT-R", " IF OUT-ST NOT = '00'", f" DISPLAY '{prog} WRITE ' OUT-ST", " END-IF", + " ADD 1 TO N", " END-IF", " END-PERFORM.", + f" DISPLAY '{prog} ' N ' RECORDS, STATUS ' IN-ST.", " CLOSE IN-F OUT-F.", " STOP RUN."])) +for name, data, size in SEQ: + (work / "data" / f"{name}.seq").write_bytes(fixed(data, size)) + +(work / "stubs" / "CEE3ABD.cbl").write_text(cobol([ + "IDENTIFICATION DIVISION.", "PROGRAM-ID. CEE3ABD.", + "* Stand-in for the Language Environment abend service: says so and ends the run with return code 16.", + "DATA DIVISION.", "LINKAGE SECTION.", "01 ABCODE PIC S9(9) BINARY.", "01 TIMING PIC S9(9) BINARY.", + "PROCEDURE DIVISION USING ABCODE TIMING.", " DISPLAY 'CEE3ABD: ABEND ' ABCODE.", " MOVE 16 TO RETURN-CODE.", " STOP RUN."])) +(work / "stubs" / "COBDATFT.cbl").write_text(cobol([ + "IDENTIFICATION DIVISION.", "PROGRAM-ID. COBDATFT.", + "* COBDATFT.asm, line for line: type 1 (YYYYMMDD) -> YYYY-MM-DD, type 2 (YYYY-MM-DD) -> YYYYMMDD, else 'INVALID INPUT'.", + "DATA DIVISION.", "LINKAGE SECTION.", "01 CO-REC.", " 05 CO-INTYPE PIC X.", " 05 CO-INPDT PIC X(20).", " 05 CO-OUTTYPE PIC X.", + " 05 CO-OUTDT PIC X(20).", " 05 CO-ERMSG PIC X(38).", + "PROCEDURE DIVISION USING CO-REC.", + " EVALUATE TRUE", + " WHEN CO-INTYPE = '1' AND CO-INPDT(5:1) NOT = '-'", " AND CO-OUTTYPE NOT = '2'", + " MOVE CO-INPDT(1:4) TO CO-OUTDT(1:4)", " MOVE '-' TO CO-OUTDT(5:1)", " MOVE CO-INPDT(5:2) TO CO-OUTDT(6:2)", + " MOVE '-' TO CO-OUTDT(8:1)", " MOVE CO-INPDT(7:2) TO CO-OUTDT(9:2)", + " WHEN CO-INTYPE = '2' AND CO-OUTTYPE NOT = '1'", + " MOVE CO-INPDT(1:4) TO CO-OUTDT(1:4)", " MOVE CO-INPDT(6:2) TO CO-OUTDT(5:2)", " MOVE CO-INPDT(9:2) TO CO-OUTDT(7:2)", + " WHEN OTHER", " MOVE 'INVALID INPUT' TO CO-ERMSG(1:13)", " END-EVALUATE.", + " MOVE 0 TO RETURN-CODE.", " GOBACK."])) +(work / "stubs" / "RUN04C.cbl").write_text(cobol([ + "IDENTIFICATION DIVISION.", "PROGRAM-ID. RUN04C.", + "* Runs CBACT04C with the PARM of INTCALC.jcl ('2022071800'), passed as z/OS passes a PARM: a halfword length, then the text.", + "DATA DIVISION.", "WORKING-STORAGE SECTION.", "01 PARMS.", " 05 PARM-LENGTH PIC S9(4) COMP VALUE 10.", " 05 PARM-TEXT PIC X(10) VALUE '2022071800'.", + "PROCEDURE DIVISION.", " CALL 'CBACT04C' USING PARMS.", " STOP RUN."])) +# the DATEPARM data set TRANREPT reads: its start and end dates, as the JCL's sort step gives them +(work / "data" / "DATEPARM.seq").write_bytes(b"2022-01-01 2022-07-06".ljust(80)) +print("prepared", sum(1 for _ in work.rglob("*") if _.is_file()), "files") diff --git a/docs/spikes/p4-13/rules.py b/docs/spikes/p4-13/rules.py new file mode 100644 index 00000000..6ad72398 --- /dev/null +++ b/docs/spikes/p4-13/rules.py @@ -0,0 +1,9 @@ +"""The reconciled rules of the published CardDemo review (reports/carddemo/reconciled/index.html), for some programs.""" +import json, re, sys +t = open(sys.argv[1]).read() +m = re.search(r"const D\s*=\s*(\{.*?\});\s*\n", t, re.S) or re.search(r"]*id=\"data\"[^>]*>(.*?)", t, re.S) +D = json.loads(m.group(1)) +wanted = set(sys.argv[2].split(",")) +out = [r for r in D["rules"] if r.get("program") in wanted] +json.dump(out, open(sys.argv[3], "w"), indent=1) +print(len(out), "rules written") diff --git a/docs/spikes/p4-13/run.sh b/docs/spikes/p4-13/run.sh new file mode 100644 index 00000000..f8ecc500 --- /dev/null +++ b/docs/spikes/p4-13/run.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# P4-13 spike: CardDemo's batch cycle under GnuCOBOL, in the container. /w is the harness's work folder (make.py). +W=/w; B=$W/bin; D=$W/run; L=$W/logs +OPTS="-std=ibm -fixed -fsign=EBCDIC -I $W/src/cpy" +export COB_LIBRARY_PATH=$B +run() { # program, then DD=file pairs; prints its return code + p=$1; shift + env "$@" $B/$p > $L/$p.out.txt 2>&1; rc=$? + echo "$p return code $rc; $(wc -l < $L/$p.out.txt) lines of output" +} + +step() { echo "== $1"; } +compile() { # name, kind (x or m), source + if cobc $OPTS -$2 -o $B/$1$( [ "$2" = m ] && echo .so ) "$3" > $L/$1.compile.txt 2>&1; then echo "compiled $1"; else echo "COMPILE FAILED $1: $(grep -m1 error $L/$1.compile.txt)"; fi +} + +if [ "$1" = one ]; then +rm -rf $B $D $L; mkdir -p $B $D $L +step "compile" +for p in CBACT01C CBACT02C CBACT03C CBCUS01C CBTRN01C CBTRN02C CBTRN03C CBSTM03A CBEXPORT CBIMPORT; do + f=$(ls $W/src/cbl/$p.* | head -1); compile $p x "$f" +done +compile CBACT04C m $W/src/cbl/CBACT04C.cbl +compile CBSTM03B m $(ls $W/src/cbl/CBSTM03B.* | head -1) +compile CEE3ABD m $W/stubs/CEE3ABD.cbl +compile COBDATFT m $W/stubs/COBDATFT.cbl +compile RUN04C x $W/stubs/RUN04C.cbl +for u in $W/util/*.cbl; do n=$(basename $u .cbl); compile $n x $u; done + +step "load the VSAM files (the JCL's IDCAMS REPRO)" +for n in ACCT CARD XREF CUST DISC TCAT TCTG TTYP; do + DD_INFILE=$W/data/$n.seq DD_OUTFILE=$D/$n.ksds $B/LOAD$n +done +cp $W/data/DALY.seq $D/DALY.seq + + +step "read programs" +run CBACT02C DD_CARDFILE=$D/CARD.ksds +run CBACT03C DD_XREFFILE=$D/XREF.ksds +run CBCUS01C DD_CUSTFILE=$D/CUST.ksds +run CBACT01C DD_ACCTFILE=$D/ACCT.ksds DD_OUTFILE=$D/ACCT.pscomp DD_ARRYFILE=$D/ACCT.arryps DD_VBRCFILE=$D/ACCT.vbps + +step "POSTTRAN: CBTRN02C posts them" +cp $D/ACCT.ksds $D/ACCT.before.ksds 2>/dev/null; DD_INFILE=$D/ACCT.ksds DD_OUTFILE=$D/ACCT.before.seq $B/DUMPACCT > /dev/null +DD_INFILE=$D/TCAT.ksds DD_OUTFILE=$D/TCAT.before.seq $B/DUMPTCAT > /dev/null +run CBTRN02C DD_DALYTRAN=$D/DALY.seq DD_TRANFILE=$D/TRAN.ksds DD_XREFFILE=$D/XREF.ksds DD_DALYREJS=$D/DALYREJS.seq DD_ACCTFILE=$D/ACCT.ksds DD_TCATBALF=$D/TCAT.ksds +DD_INFILE=$D/TRAN.ksds DD_OUTFILE=$D/TRAN.posted.seq $B/DUMPTRAN +DD_INFILE=$D/ACCT.ksds DD_OUTFILE=$D/ACCT.posted.seq $B/DUMPACCT +DD_INFILE=$D/TCAT.ksds DD_OUTFILE=$D/TCAT.posted.seq $B/DUMPTCAT + +step "CBTRN01C: validate the daily transactions (it reads the posted transaction file)" +run CBTRN01C DD_DALYTRAN=$D/DALY.seq DD_CUSTFILE=$D/CUST.ksds DD_XREFFILE=$D/XREF.ksds DD_CARDFILE=$D/CARD.ksds DD_ACCTFILE=$D/ACCT.ksds DD_TRANFILE=$D/TRAN.ksds + +step "INTCALC: CBACT04C computes interest, PARM='2022071800'" +run RUN04C DD_TCATBALF=$D/TCAT.ksds DD_XREFFILE=$D/XREF.ksds DD_ACCTFILE=$D/ACCT.ksds DD_DISCGRP=$D/DISC.ksds DD_TRANSACT=$D/SYSTRAN.seq +DD_INFILE=$D/ACCT.ksds DD_OUTFILE=$D/ACCT.interest.seq $B/DUMPACCT + +echo "phase one done" +exit 0 +fi + +if [ "$1" = two ]; then +step "TRANREPT: CBTRN03C on the sorted transactions (the sort ran outside, as DFSORT's stand-in)" +run CBTRN03C DD_TRANFILE=$D/TRAN.sorted.seq DD_CARDXREF=$D/XREF.ksds DD_TRANTYPE=$D/TTYP.ksds DD_TRANCATG=$D/TCTG.ksds \ + DD_DATEPARM=$W/data/DATEPARM.seq DD_TRANREPT=$D/TRANREPT.txt + +step "CREASTMT: CBSTM03A writes the statements" +run CBSTM03A DD_STMTFILE=$D/STATEMNT.txt DD_HTMLFILE=$D/STATEMNT.html DD_TRNXFILE=$D/TRAN.ksds DD_XREFFILE=$D/XREF.ksds DD_CUSTFILE=$D/CUST.ksds DD_ACCTFILE=$D/ACCT.ksds +echo "phase two done" +fi diff --git a/docs/spikes/p4-13/sort.py b/docs/spikes/p4-13/sort.py new file mode 100644 index 00000000..df012861 --- /dev/null +++ b/docs/spikes/p4-13/sort.py @@ -0,0 +1,10 @@ +"""DFSORT's stand-in for TRANREPT.jcl: SORT FIELDS=(TRAN-CARD-NUM,A), INCLUDE TRAN-PROC-DT between the JCL's dates. +CVTRA05Y: TRAN-CARD-NUM at offset 262 (16 bytes), TRAN-PROC-TS at 304 (its first 10 bytes are the date). 350-byte records.""" +import sys +data = open(sys.argv[1], "rb").read() +recs = [data[i:i + 350] for i in range(0, len(data), 350)] +start, end = (sys.argv[3].encode(), sys.argv[4].encode()) if len(sys.argv) > 4 else (b"2022-01-01", b"2022-07-06") +kept = [r for r in recs if start <= r[304:314] <= end] +kept.sort(key=lambda r: r[262:278]) # a stable sort, as EQUALS keeps the input order of equal keys +open(sys.argv[2], "wb").write(b"".join(kept)) +print(f"sort: {len(recs)} in, {len(kept)} kept")