<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sumanta pakira on Medium]]></title>
        <description><![CDATA[Stories by Sumanta pakira on Medium]]></description>
        <link>https://medium.com/@sumantapakira?source=rss-960b13202097------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Sumanta pakira on Medium</title>
            <link>https://medium.com/@sumantapakira?source=rss-960b13202097------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:14:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumantapakira/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Faithfulness Must be the
Leading Evaluation Criterion of Clinical Knowledge Graph]]></title>
            <link>https://sumantapakira.medium.com/faithfulness-must-be-the-leading-evaluation-criterion-of-clinical-knowledge-graph-463ff77fe5d6?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/463ff77fe5d6</guid>
            <category><![CDATA[structural-hallucination]]></category>
            <category><![CDATA[clinical-ai-faithfulness]]></category>
            <category><![CDATA[topology-constrained]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[graph-attention-networks]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 08:23:59 GMT</pubDate>
            <atom:updated>2026-06-01T21:06:18.629Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Abstract</strong>: Clinical Graph-LLMs achieve high benchmark accuracy while bypassing their knowledge graphs — a failure we term Structural Hallucination. Correctness via memorisation rather than graph traversal is a safety risk: such models cannot be trusted when evidence is updated or in rare-disease settings where parametric priors are absent.<br>I formalise the Structural Alignment Score (SAS), measuring causal sensitivity to Counterfactual Edge Deletion (e∗ removed from G):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*xxlvkQqFXaUGcoHCwEls2A.png" /></figure><p>State-of-the-art Graph-LLMs score SAS ≈ 0.00, confirming their correct predictions are structurally fraudulent. We propose Topology-Constrained Decoding(TCD), which hard-masks the LLM logit distribution to KGverified neighbours at step 0, raising KG-grounded token probability from 0.33% to 100% (+99.7 pp, BioGPT) with SAS ≈ 0.94 and zero hallucination by construction. GAT-TCD extends this with a 2-layer Graph Attention Network that ranks the constraint set by structural relevance, achieving SAS ≈ 1.00 on primary therapeutic edges (e.g., Imatinib→ABL1) while deliberately yielding SAS ≈ 0.23 under random CED — concentrating faithfulness where clinical evidence is strongest. PrimeKG-trained GAT weights rank biologically plausible targets (e.g. artenimol: CYCS top-1, GAPDH rank-2) and CED shifts generations when the top node is removed (3/10 drugs, step-0 SAS = 30% under prefix-TCD). We introduce Transparency Debt to frame the systemic risk of deploying accurate but structurally unfaithful models,<br>and call on the community to adopt SAS as a standard reporting metric alongside accuracy.</p><ol><li><strong>Introduction</strong><br>Graph-LLMs ground LLM reasoning in verifiable KGs such as PrimeKG [1], promising traceable clinical diagnostics — but this promise rests on a precarious foundation.</li></ol><p><em>Structural Hallucination</em> occurs when a model produces a correct clinical ansIr by bypassing the supplied graph and drawing on parametric memory instead of graph evidence.</p><p>To illustrate, consider the Phone-Charger Trap: even when the critical biological edge (Imatinib, inhibits, BCR-ABL) is explicitly removed from the input graph, state-of-the-art mod-els such as G-Retriever [2] continue to predict the same relationship. The model’s reasoning is decoupled from the graph structure entirely — a finding I characterise formally through the CED<br>protocol (Section 3) and case study (Section 7.6).<br><br>This failure exposes growing Transparency Debt (defined formally in Section 8). While models maintain high benchmark accuracy, they remain structurally unfaithful. In clinical settings — where the validity of a specific causal pathway (e.g., genomic mutation → disease progression) is more<br>critical than a general probabilistic prediction — this decoupling is a safety risk.</p><p>I therefore argue that for clinical Graph-LLMs, structural faithfulness must be treated as a mandatory prerequisite rather than an optional secondary property. My contributions are:<br>• I expose Structural Hallucination via CED experiments on PrimeKG and formalise SAS (Jensen-Shannon Divergence) to quantify structural faithfulness (Sections 3, 4).<br>• I propose TCD, which hard-masks the LLM logit distribution to KG neighbours at inference time, making hallucination impossible by construction (Section 5).<br>• I extend TCD to GAT-TCD, using a 2-layer GAT to attention-rank the constraint set, achieving SAS ≈ 1.00 on primary therapeutic edges (Section 7.4).<br>• I show that PrimeKG-trained GAT weights improve semantic ranking and CED-shifted generations (e.g. artenimol: CYCS→GAPDH after node deletion; Section 7.5).<br>• I evaluate on 5 drugs across BioGPT, demonstrating +97–100 pp KG-grounding improvement with zero hallucination by construction (Section 7).</p><p><strong>2. Background and Related Work</strong></p><p><strong>2.1 Precision Medicine Knowledge Graph (PrimeKG)</strong></p><p>PrimeKG [1] is a large-scale biomedical knowledge graph integrating 20 public databases including DrugBank, UniProt, and the Disease Ontology. It encodes:</p><ul><li>8,100,498 edges spanning 10 node types and 30 relation types<br>• 25,653 drug–protein edges (relations: target, enzyme, carrier, transporter)<br>• 2,085 drugs with ≥ 3 known protein targets<br>• 2,836 unique protein names stored as HGNC official gene symbols</li></ul><p>I use PrimeKG as the sole source of ground truth for drug–protein targeting relationships.</p><p><strong>2.2 G-Retriever and Graph-RAG</strong></p><p>G-Retriever [2] retrieves a task-relevant subgraph from a KG using Prize-Collecting Steiner Tre (PCST) optimisation, converts it to a textual description, and conditions a language model on this description via soft prompting. The model is not architecturally constrained by graph structure; it receives the graph as natural-language context. A growing body of Graph-RAG literature [3, 4] follows the same soft-prompting paradigm, making the structural-faithfulness problem I identify broadly applicable.</p><p><strong>2.3 Constrained Decoding</strong></p><p>Constrained decoding methods restrict the output vocabulary at inference time. Early work focused on grammatical constraints using finite-state automata [8] and trie-based lexically constrained beam search [9]. More recent methods enforce structured knowledge extraction [10]. To my knowledge, no prior work enforces graph-topological constraints directly on the logit distribution of a Graph-LLM at each decoding step — the contribution of TCD.</p><p><strong>3. The Crisis of Clinical Faithfulness</strong></p><p>Traditional accuracy metrics fail to distinguish betIen topological reasoning and semantic recall. I define a failure of faithfulness as a model’s inability to update its diagnostic reasoning when the underlying graph structure is altered.</p><p><strong>3.1 The Counterfactual Edge Deletion (CED) Protocol</strong></p><p>To evaluate structural faithfulness, I introduce the CED protocol. For a test drug D and one of its KG-verified target proteins R, I construct a perturbed graph G′ by removing the critical edge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*PowPucyBHNls1AbjnaxR9w.png" /></figure><p>I then query the model using an identical prompt under both G (full graph) and G′ (CED graph), and compare the model’s output distributions. A structurally faithful model should reflect the absence of evidence when e∗ is removed.</p><p><strong>3.2 Observing Structural Hallucination</strong></p><p>Empirical observations reveal that current Graph-LLMs consistently exhibit Structural Hallucination: despite the removal of e∗, the baseline model continues to predict the existence of the deleted relationship with high confidence (Table 5, SAS = 0.00). The model’s predictions are dominated by pre-trained transformer representations rather than the supplied graph.<br>This behaviour is especially dangerous in rare disease or drug-repurposing scenarios, where pre-training data may be limited or conflicting. In such settings, structural unfaithfulness is not merely a limitation — it is a clinical liability.</p><p><strong>4 Measuring Faithfulness: The Structural Alignment Score</strong></p><p><strong>4.1 Mathematical Formulation</strong></p><p>Let G = (V, E) denote a clinical knowledge graph derived from PrimeKG, with biological entities V and therapeutic relationships E. Given a natural language query q, a Graph-LLM produces a probability distribution over vocabulary V. I define the factual distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*urpsRcR94KIjtPD3ieQbew.png" /></figure><p>and the counterfactual distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*5qQk66SZL_jDMMpmlQZ8aw.png" /></figure><p>where G′ = G \ {e∗}. The Structural Alignment Score is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*D9bGHPB6VJvP0H5sfGLihw.png" /></figure><p>where the Jensen-Shannon Divergence is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNt852Q2DO98omAEe7lcWw.png" /></figure><p>For experimental tractability I operationalise SAS as a binary per-sample indicator (Section 6.5), which preserves the intuition of Eq. 4 while enabling measurement at the token level without requiring full vocabulary probability comparisons.</p><p><strong>4.2 Interpretation</strong></p><p>SAS is bounded in [0, 1]:</p><p><strong>High SAS (SAS → 1): </strong>The model’s output is causally sensitive to graph topology. Removing e∗ shifts the predicted distribution, indicating that the model reasons from the provided structure.</p><p><strong>Low SAS (SAS → 0):</strong> The model’s output remains invariant under topological perturbation — <em>Structural Decoupling</em>. The model draws on internal parametric knowledge rather than the supplied graph.</p><p><strong>Clinical implication:</strong> A model may achieve high accuracy while exhibiting SAS ≈ 0, meaning its correct predictions are structurally fraudulent: they arrive at the right ansIr for the wrong reason, rendering the system untrustworthy in any out-of-distribution scenario.</p><p><strong>5 Topology-Constrained Decoding (TCD)</strong></p><p>5.1 Motivation: From Soft Suggestions to Hard Constraints</p><p>Existing Graph-LLM approaches treat the knowledge graph as a passive context provider. TCD fundamentally redefines the role of the graph: it enforces graph structure as a hard decoding constraint, making Structural Hallucination impossible by construction.</p><p>5.2 GAT-Informed Topological Action Space</p><p>I encode the local structure of the clinical knowledge graph using a Graph Attention Network (GAT), which captures k-hop neighbourhood dependencies. For active entity vi ∈ V , I define <em>the Topological Action Space:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*NF7G3vTlSwRWZv9MHMoeCw.png" /></figure><p>where Nk(vi) is the set of valid k-hop neighbours of vi in PrimeKG mapped to LLM vocabulary tokens, and Vsyn is a set of permissible medical syntax tokens (e.g., inhibits, treats)</p><p>5.3 Logit Masking Mechanism</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fi5JHT1Wp0SvAvKZJYBceA.png" /></figure><p>The masked logits and next-token distribution are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*egZILAQebBNpibxgDv3Lxw.png" /></figure><p>By assigning −∞ to all tokens outside At, TCD guarantees that any generated entity corresponds to a valid edge in the graph, eliminating Structural Hallucination by construction.</p><p>5.4 Efficient Implementation via Sparse Bitmasking</p><p>The vocabulary size (|V| ≈ 50K) and the graph size (|V | ≈ 130K) motivate an efficient implementation. I precompute the adjacency structure of PrimeKG as a compressed bit-array indexed by node identifier. At each decoding step, the valid action space At is retrieved via an O(1) hash lookup, without expensive recomputation. Theoretically, this design bounds masking overhead to O(|V|) per step, which is dominated by the softmax normalisation already present in unconstrained decoding.<br>The prompt-aware variant implemented here fires the constraint exclusively at generation step 0 (i.e., when len(input ids) == prompt length), preventing the processor from erroneously activating on entity tokens within the prompt itself — a critical correctness fix over naıve implementations.</p><p><strong>6. Experimental Setup</strong></p><p>We filter PrimeKG to directed drug→protein edges, yielding 25,653 edges across 2,085 drugs, then select five single-word drugs ranked by target count for evaluation with GPT-2 and BioGPT. Each drug is probed via the prompt ‘‘{Drug} targets the protein’’, measuring KG-grounding<br>probability (Metric A), entity precision on 20 generated tokens (Metric B), and binary SAS under Counterfactual Edge Deletion (Metric C)</p><p><strong>6.1 Knowledge Graph Preprocessing</strong></p><p>PrimeKG edges Ire filtered to directed drug→protein edges: x type = “drug”, y type =“gene/protein”, display relation ∈ {target, enzyme, carrier,transporter}. This yielded 25,653 edges spanning 2,085 drugs. Drug and protein names Ire loIrcased. Only drugs with ≥ 3 known protein targets Ire retained to ensure a non-trivial constraint vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_Zg4BBzLIbBzXK7CzIOig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifLABXPvOWmM8VCKRk3lHw.png" /></figure><p><strong>6.2 Drug Selection</strong></p><p>Ten single-word drug names Ire selected, ranked by target count. Multi-word names (e.g., “zincacetate”) Ire excluded to avoid tokenisation ambiguity. Table 1 lists all evaluated drugs. “First-Tokens” counts the distinct first subword token IDs that map across all protein names in a<br>drug’s target set. A loIr count means feIr alloId tokens under TCD, making the constraint more aggressive.</p><p><strong>6.3 Language Models</strong></p><p>Two causal language models are evaluated: GPT-2 (gpt2, 117M parameters), trained on IbText (general Ib corpus), serves as a domain-agnostic baseline to verify TCD mechanics independently of biomedical knowledge. BioGPT (microsoft/biogpt, 347M parameters), trained on 15 million PubMed abstracts, provides biomedical domain knowledge and generates protein class terminology (“kinase”, “phosphatase”) as Ill as specific protein aliases.</p><p><strong>6.4 Prompt Template</strong></p><p>All experiments used: Fact: {Drug} targets the protein, where {Drug} is the title-cased drug name. The model completes the sentence with a protein name.</p><p><strong>6.5 Metrics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZbdPPVeGO2bzQwx0vSsbQ.png" /></figure><p><strong>7. Results</strong></p><p><strong>7.1 Token Probability Analysis (Metric A)</strong></p><p>Tables 2 report the probability mass on known-target first-tokens at generation step 0, before and after applying TCD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7gzRdDc-KRpuR1wR_JmcA.png" /></figure><p>A noteworthy finding is that BioGPT’s baseline target probability (0.333%) is low than GPT-2’s (2.752%), despite BioGPT being the domain-specific model. BioGPT concentrates probability mass on protein class tokens (kinase: 32–57%, phosphatase: 13–27%) rather than specific gene sym-<br>bols, yielding less natural probability on the ∼7–105 target first-tokens per drug. GPT-2 distributes probability more uniformly, accidentally assigning slightly more mass to target tokens. This illustrates that domain-specialised models can increase categorical hallucination even as they reduce<br>surface-form incoherence.</p><p><strong>7.2 Generated Text Analysis (Metric B)</strong></p><p>Table 3 shows illustrative BioGPT continuations. Unconstrained baselines and Flat-TCD (step-0only) often emit common names or aliases (SHP-1, p97 / VCP, PKC-α) that fail exact PrimeKG symbol matching but are biologically meaningful. With NER+HGNC Metric B (Section 6.5), 6 trained GAT-TCD + prefix-TCD achieves 100% entity precision on the 10-drug run whenever a<br>KG protein is resolved (Section 7.5); e.g. acy1, cycs, and gapdh for copper and artenimol link to verified targets, while alias-only baseline strings still score zero under exact matching.</p><p>Table 3: Generation examples (BioGPT, 20 new tokens). “Exact match” = legacy Metric B (PrimeKG symbol string only). “NER+HGNC” = spaCy NER + HGNC alias resolution (trained GAT-TCD + prefix-TCD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRIyfr6bBREzsiZPnL0krw.png" /></figure><p>Table 4 documents alias–symbol pairs that confuse exact matching but are resolved by HGNC (e.g.hERG → KCNH2). The mismatch is therefore primarily a surface-form issue at generation time, not a failure to identify correct biology once aliases are normalised at evaluation time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR2BY4vL7054MUpdYA_5Qw.png" /></figure><p><strong>7.3 Accuracy vs. Structural Faithfulness (Table 1)</strong></p><p>Both TCD variants raise F1 to 100% and reduce hallucination to 0% (Table 5). Flat-TCD: SAS ≈0.94 uniformly. GAT-TCD: SAS ≈ 1.00 on primary targets (targeted CED), ≈ 0.23 on random CED — concentrating sensitivity where evidence is strongest. Baselines: SAS = 0.00, provably, as no graph is consulted. Full derivation in Section 7.4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoTd6M9W6Uv4jwzzJAFzSQ.png" /></figure><p><strong>7.4 GAT-TCD: Attention-Iighted Structural Sensitivity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1yUs_Hao2_YT0Bhxh9NMQ.png" /></figure><p><strong>Constraint selectivity.</strong> Table 6 reports the reduction in constraint size for k = 20. For drugs with many targets (fostamatinib, copper), GAT-TCD prunes 73–77% of the flat token set, concentrating decoding pressure on the structurally most relevant proteins. For drugs where the flat set already has<br>≤ k unique tokens (ethanol, phenytoin, lamotrigine, enflurane), GAT-TCD is equivalent to Flat-TCD and the reduction is 0%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQJGiZbSMdrQzL-j7EIkKA.png" /></figure><p><strong>Interpretation of differential SAS</strong>. GAT-TCD’s low random-CED SAS for drugs with many tar-gets (fostamatinib: 0.06) is not a faithfulness failure. It reflects that most proteins in a 306-targetpharmacological profile are indirect, low-confidence interactions. A model that is insensitive to the<br>removal of a low-attention peripheral association is correctly prioritising high-evidence structure. Flat-TCD cannot make this distinction: it treats every target in PrimeKG as equally critical. GAT-TCD’s high random-CED SAS for drugs with few targets (ethanol, phenytoin, lamotrigine:0.94) arises because GAT-TCD equals Flat-TCD in those cases — all proteins fit within the top-k window, so no pruning occurs and every CED perturbation is detected.</p><p><strong>7.5 Trained GAT Improves CED Ranking and KG-Grounded Generation</strong></p><p>Random-init GAT-TCD re-weights neighbours by subgraph topology alone; it can rank high-degree or structurally central nodes without pharmacological meaning. We therefore pre-train ϕ on PrimeKG drug→protein link prediction (positive edges vs. sampled negatives; train gat tcd.py), then load the checkpoint at inference ( — gat-checkpoint)</p><p>Experimental protocol. I evaluate n = 10 single-word drugs on<br>BioGPT with — gat-checkpoint, — prefix-tcd, and NER+HGNC Metric B<br>(primekg hallucination eval.py). Table 7 summarises aggregate behaviour; Table 8 lists representative CED continuations after removing the GAT top-1 protein and re-running ϕ on the reduced subgraph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srKKxcWJBvBbyELBL1TumA.png" /></figure><p>Case study: artenimol (CYCS → GAPDH under CED). Artenimol has 84 KG-verified targets; trained GAT-TCD retains 19 first-tokens (top-20 proteins). The bilinear scorer ranks CYCS first (score 8.21) and GAPDH second (8.17) — both are PrimeKG target edges. Prefix-TCD on the full graph yields:</p><p><em>Fact: Artenimol targets the protein cycs inhibits the ATPase activity of the enzyme.</em></p><p>Metric B resolves cycs as a correct target (100% precision for this drug). Under true graph CED we remove cycs, re-run the GAT (83 edge rows remain), and prefix-decode from the new top-k list; GAPDH rises to rank-1 and the CED sentence becomes:</p><p><em>Fact: Artenimol targets the protein gapdh to inhibit the synthesis<br>of the toxin.</em></p><p>The step-0 token changes (full=’s’, ced=’p’ ⇒ SASi=1). gapdh is KG-grounded; the toxin clause is unconstrained LLM completion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zq-a-AmKKeSDLH103KY0LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WexAhBeBOUmJWC3YkVapg.png" /></figure><p><strong>How this helps the knowledge graph.</strong> Trained GAT-TCD turns PrimeKG from passive prompt text into an active, auditable decoding prior:</p><ol><li><strong>Training signal:</strong> ϕ is fit to predict which (D, p) edges exist in PrimeKG, so scores align with the same relation inventory used as ground truth.</li><li><strong>Smaller, semantic constraint sets:</strong> On 10 drugs, GAT-TCD averages 13.1 allowed tokens vs. 40.5 for Flat-TCD (67.7% reduction), keeping pharmacologically related neighbours (e.g. CYCS, GAPDH, LDHA for artenimol).</li><li><strong>Traceability:</strong> Every prefix-forced protein maps to a PrimeKG node; the generating path can be logged as (D, target, p) plus GAT score.</li><li><strong>Structural accountability:</strong> CED with GAT re-forward changes the forced protein on 3/10 drugs at step 0 (SAS = 30%); full-sentence CED shifts (Table 8) show the model remains inside the KG while updating its stated target when evidence is removed.</li><li><strong>Updateability</strong>: When PrimeKG is revised, retraining or re-ranking changes AGAT without retraining the LLM — the graph remains the source of truth for what may be said about targets.</li></ol><p><strong>7.6 Case Study: Probing the Imatinib–BCR-ABL Pathway</strong></p><p>To illustrate the practical stakes of Structural Hallucination, I conducted a deep-dive analysis on the Imatinib–BCR-ABL axis in PrimeKG.</p><p><strong>7.6.1 Setup</strong></p><p>I presented the model with a 2-hop subgraph centred on Imatinib (DrugBank: DB00619). In the Control Group, the subgraph included the direct edge (Imatinib, inhibits, BCR-ABL). In the CED Group, this edge was removed, leaving only downstream signalling and metabolic connections<br>(e.g., CYP3A4).</p><p><strong>7.6.2 Reasoning Traces</strong></p><p>Table 10 summarises the divergence in model behaviour. The baseline model recites its pre-trained knowledge of Imatinib regardless of what evidence is provided, achieving an SAS of ≈ 0.00. Flat-TCD adapts its output to the available graph evidence, achieving SAS = 0.83. GAT-TCD goes further: because ABL1 occupies the top attention rank in Imatinib’s subgraph, its CED removal is immediately detected and the output shifts to KIT (rank 2 by attention), achieving SAS = 1.00.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1grvLJoSvSnUAqWz7SgE6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dvFnmYKf_Y_ImPVsFBTUQ.png" /></figure><p>While soft-prompting offers a nominal improvement over the baseline (SAS = 0.08), it fails to force a reasoning shift when evidence is removed. Only hard topological constraints — enforced at the logit level — are sufficient to ensure faithfulness to clinical graph evidence. GAT-TCD further improves over Flat-TCD by exploiting the attention ranking to make the output maximally sensitive (SAS = 1.00) to the deletion of a primary therapeutic edge.</p><p><strong>8 Discussion: The Ethics of Traceability</strong></p><p><strong>8.1 Responsibility and Evidence-Based AI</strong><br>Correctness without traceability is unreliable; TCD fixes this by mapping every output token to an auditable PrimeKG edge.</p><p><strong>8.2 The Transparency Debt</strong><br><em>Transparency Debt</em> is the deferred risk of optimising clinical AI for performance while ignoring auditability — a systemic liability once deployed at scale. TCD repays this debt by embedding hard structural constraints at inference time.</p><p><strong>9 Limitations</strong></p><p><strong>Single-token scope.:</strong>Vanilla TCD constrains only the first token; prefix-TCD<br>(PrefixTCDProcessor) extends masking until a complete PrimeKG gene symbol is emit-ted, but trailing mechanism text remains unconstrained.</p><p><strong>Symbol mismatch (evaluation vs. decoding):</strong> PrimeKG stores HGNC gene symbols while un-constrained LLMs emit common names and aliases (e.g. hERG vs. KCNH2). For Metric B we resolve mentions via the HGNC complete set, spaCy biomedical NER, and fuzzy linking ( — use-ner),<br>which removes the false-zero precision seen under exact symbol matching (Table 3). This does not remove the mismatch at generation time: baseline and Flat-TCD outputs may still display aliases unless prefix-TCD forces symbols from the KG constraint set; mechanism phrases after the prefix<br>are not KG-verified, and NER can mis-link peripheral terms (e.g. pathway names).</p><p><strong>Drug selection:</strong> The primary token-probability tables use 5 high-target drugs; the trained-GAT evaluation uses 10 single-word drugs; selective agents (imatinib, sildenafil) would yield more informative qualitative traces.</p><p><strong>10 Conclusion</strong></p><p>I formalised Structural Hallucination, introduced SAS to quantify it, and proposed TCD to eliminate it — raising KG-grounded token probability from &lt; 1% to 100% with zero hallucination by construction; GAT-TCD further achieves SAS ≈ 1.00 on primary therapeutic edges via attention-ranked<br>constraint selection, and PrimeKG-trained ϕ improves semantic ranking and CED-shifted outputs on PrimeKG (Section 7.5). The clinical NLP community must adopt SAS alongside accuracy and treat structural faithfulness as a deployment prerequisite, not a research curiosity.</p><p><strong>References</strong></p><p>[1] P. Chandak, K. Huang, and M. Zitnik. Building a knowledge graph to enable precision medicine.<br>Scientific Data, 10(1):67, 2023.<br>[2] X. He, Y. Tian, Y.-F. Sun, N. Chawla, T. Laurent, Y. LeCun, X. Bresson, and B. Hooi. G-<br>Retriever: Retrieval-augmented generation for textual graph understanding and question ansIr-<br>ing. In Advances in Neural Information Processing Systems (NeurIPS), 2024.<br>[3] D. Edge, H. Trinh, N. Cheng, J. Bradley, A. Chao, A. Mody, S. Truitt, and J. Larson. From<br>local to global: A graph RAG approach to query-focused summarization. arXiv preprint<br>arXiv:2404.16130, 2024.<br>[4] B. Peng, H. Liu, W. Ii, J. Du, Z. Wang, Y. Chen, and J. Han. Graph retrieval-augmented gener-<br>ation: A survey. arXiv preprint arXiv:2408.08921, 2024</p><p>[5] P. Veliˇckovi´c, G. Cucurull, A. Casanova, A. Romero, P. Li`o, and Y. Bengio, “Graph Attention<br>Networks,” in International Conference on Learning Representations (ICLR), 2018.<br>[6] Z. Ji, N. Lee, R. Frieske, T. Yu, D. Su, Y. Xu, E. Ishii, Y. Bang, A. Madotto, and P. Fung. Survey<br>of hallucination in natural language generation. ACM Computing Surveys, 55(12):1–38, 2023.<br>[7] K. Shuster, S. Poff, M. Chen, D. Kiela, and J. Iston. Retrieval augmentation reduces hallucina-<br>tion in conversation. In Findings of EMNLP, 2021.<br>[8] M. Post and D. Vilar. Fast lexically constrained decoding with dynamic beam allocation for<br>neural machine translation. In Proceedings of NAACL-HLT, 2018.<br>[9] P. Anderson, B. Fernando, M. Johnson, and S. Gould. Guided open vocabulary image captioning<br>with constrained beam search. In Proceedings of EMNLP, 2017.<br>[10] P. De Cao, W. Aziz, and I. Titov. Autoregressive entity retrieval. In Proceedings of ICLR,<br>2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=463ff77fe5d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Job Scheduler]]></title>
            <link>https://sumantapakira.medium.com/distributed-job-scheduler-f9d6b70b771a?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d6b70b771a</guid>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 09:55:29 GMT</pubDate>
            <atom:updated>2023-01-25T14:40:40.908Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to build an asynchronous distributed Job Scheduler that handles around 50k requests per day.</p><p>This architecture is built using four components-</p><ol><li>Springboot app which sends the request for scheduling</li><li>SQS (Simple Queue Service) which is responsible for queueing the initial load</li><li>Dynamo DB for storing the job scheduling information</li><li>Kubernetes for managing the PODs responsible for scheduling the jobs</li></ol><figure><img alt="Distributed job scheduler" src="https://cdn-images-1.medium.com/max/640/1*HrpGIfdQo_V7jvIYMiiQ7w.jpeg" /><figcaption>High-level archritechture</figcaption></figure><p>The complete application is divided into 3 parts. In the first part, we are going to learn about why and how the Spring boot application creates an item into SQS and then how store the Job information into Dynamo DB.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIpluCICnVyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIpluCICnVyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIpluCICnVyA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e7e657d4e7e091465c43b2f7ed4e624/href">https://medium.com/media/2e7e657d4e7e091465c43b2f7ed4e624/href</a></iframe><p>In the second part, we are going to learn again why and how Dynamo DB sharding is used and how Kubernetes PODs are mapped to those Dynamo DB shardings.</p><figure><img alt="Kubernetes PODs" src="https://cdn-images-1.medium.com/max/1024/1*khZ1VTfrxr0uhFAnzy2IkQ.jpeg" /><figcaption>Dynamo DB based scheduling</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d6b70b771a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JVM Classloader leak]]></title>
            <link>https://sumantapakira.medium.com/jvm-classloader-leak-cddaa35f7aec?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/cddaa35f7aec</guid>
            <category><![CDATA[classloading]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[meatspace]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Fri, 03 Sep 2021 10:38:16 GMT</pubDate>
            <atom:updated>2021-09-03T10:38:16.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was analyzing the heap dumps and learnt about how classloader leak occurs.</p><p>Let&#39;s see this code example to understand how classloader leaks possible</p><pre>Main.java</pre><pre>-----------------------------------------</pre><pre><strong>public</strong> <strong>class</strong> Main {</pre><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String...args) <strong>throws</strong> Exception {</pre><pre>List&lt;Object&gt; list = <strong>new</strong> ArrayList&lt;&gt;();</pre><pre>loadClass(list);</pre><pre><strong>while</strong> (<strong>true</strong>) {</pre><pre>System.gc();</pre><pre>Thread.sleep(1000);</pre><pre>}</pre><pre>}</pre><pre><strong>private</strong> <strong>static</strong> <strong>void</strong> loadClass(List list) <strong>throws</strong> Exception {</pre><pre>URL url = Main.<strong>class</strong>.getProtectionDomain().getCodeSource().getLocation();</pre><pre>MyCustomClassLoader cl = <strong>new</strong> MyCustomClassLoader(url);</pre><pre>Class&lt;?&gt; clazz = cl.loadClass(&quot;com.test.Foo&quot;);</pre><pre>list.add(clazz.newInstance());</pre><pre>cl = <strong>null</strong>;</pre><pre>}</pre><pre>}</pre><pre><strong>class</strong> MyCustomClassLoader <strong>extends</strong> URLClassLoader {</pre><pre><strong>public</strong> MyCustomClassLoader(URL... urls) {</pre><pre><strong>super</strong>(urls, <strong>null</strong>);</pre><pre>}</pre><pre>@Override</pre><pre><strong>protected</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println(&quot;*** CustomClassLoader finalized!&quot;);</pre><pre>}</pre><pre>}</pre><pre>Foo.java</pre><pre>----------------------------------</pre><pre><strong>public</strong> <strong>class</strong> Foo {</pre><pre><strong>public</strong> Foo() {</pre><pre>System.out.println(&quot;Test ClassLoader: &quot; + <strong>this</strong>.getClass().getClassLoader());</pre><pre>}</pre><pre>@Override</pre><pre><strong>protected</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println( <strong>this</strong> + &quot; finalized!&quot;);</pre><pre>   }</pre><pre>}</pre><p>The output of this is as follows:</p><p>Test ClassLoader: com.test.MyCustomClassLoader@71dac704</p><p>So, here we can see “*** <em>CustomClassLoader finalized!</em>” is not called and this is because MyCustomClassLoader is holding a reference of object <em>list </em>as the instances loaded by classloader are kept in it.</p><p>Now, let&#39;s change the code a bit, so here we will set <em>list</em> to null</p><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String...args) <strong>throws</strong> Exception {</pre><pre>List&lt;Object&gt; list = <strong>new</strong> ArrayList&lt;&gt;();</pre><pre>loadClass(list);</pre><pre><strong>while</strong> (<strong>true</strong>) {</pre><pre>System.gc();</pre><pre>Thread.sleep(1000);</pre><pre>list = <strong>null</strong>;</pre><pre>}</pre><pre>}</pre><p>And now see the output</p><p>Test ClassLoader: com.test.MyCustomClassLoader@71dac704<br>com.test.Foo@650de12 finalized!<br>*** CustomClassLoader finalized!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cddaa35f7aec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JVM OutOfMemory — Meta Space]]></title>
            <link>https://sumantapakira.medium.com/jvm-outofmemory-meta-space-f3c10e61e5e2?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c10e61e5e2</guid>
            <category><![CDATA[out-of-memory]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oom]]></category>
            <category><![CDATA[meatspace]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 23:53:19 GMT</pubDate>
            <atom:updated>2021-08-05T00:03:26.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>JVM OutOfMemory — Meta Space</h3><p>I think as a programmer at least one time in your carrier you have come across the OutofMemory issue. In this tutorial, I will explain to you my experience with Heap dump analysis and what you have to check while doing heap dump analysis.</p><p>In this tutorial, I will focus on out-of-memory Metaspace. If you are not aware of what Metaspace is then I would suggest you read <a href="https://wiki.openjdk.java.net/display/HotSpot/Metaspace">this</a>.</p><p>There are 4 scenarios that I have come across which could cause Metaspace error</p><ol><li>Classloader leak — Thread Local variables</li><li>Duplicate objects</li><li>OSGI Class loader leak</li><li>Metaspace size is less</li></ol><p>Lets first understand how classloader leak occurs in the below code. <strong>Threadlocal variables</strong> is not removed after creating it. In a web application, instead of creating a new thread every time, it is followed to use the concept of Thread pool.</p><pre>Main.java</pre><pre>--------------</pre><pre><strong>public</strong> <strong>class</strong> Main {</pre><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String...args) <strong>throws</strong> Exception {</pre><pre>loadClass();</pre><pre><strong>while</strong> (<strong>true</strong>) {</pre><pre>System.gc();</pre><pre>Thread.sleep(1000);</pre><pre>}</pre><pre>}</pre><pre><strong>private</strong> <strong>static</strong> <strong>void</strong> loadClass() <strong>throws</strong> Exception {</pre><pre>URL url = Main.<strong>class</strong>.getProtectionDomain().getCodeSource().getLocation();</pre><pre>MyCustomClassLoader cl = <strong>new</strong> MyCustomClassLoader(url);</pre><pre>Class&lt;?&gt; clazz = cl.loadClass(&quot;com.test.Foo&quot;);</pre><pre>clazz.newInstance();</pre><pre>cl = <strong>null</strong>;</pre><pre>}</pre><pre>}</pre><pre><strong>class</strong> MyCustomClassLoader <strong>extends</strong> URLClassLoader {</pre><pre><strong>public</strong> MyCustomClassLoader(URL... urls) {</pre><pre><strong>super</strong>(urls, <strong>null</strong>);</pre><pre>}</pre><pre>@Override</pre><pre><strong>protected</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println(&quot;*** CustomClassLoader finalized!&quot;);</pre><pre>}</pre><pre>}</pre><pre>Foo.java</pre><pre>------------------------------</pre><pre><strong>public</strong> <strong>class</strong> Foo {</pre><pre><strong>private</strong> <strong>static</strong> <strong>final</strong> ThreadLocal&lt;Bar&gt; tl = <strong>new</strong> ThreadLocal&lt;Bar&gt;();</pre><pre><strong>public</strong> Foo() {</pre><pre>Bar bar = <strong>new</strong> Bar();</pre><pre>tl.set(bar);</pre><pre>System.out.println(&quot;Test ClassLoader: &quot; + <strong>this</strong>.getClass().getClassLoader());</pre><pre>}</pre><pre>@Override</pre><pre><strong>protected</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println( <strong>this</strong> + &quot; finalized!&quot;);</pre><pre>}</pre><pre>}</pre><pre>Bar.java</pre><pre>----------------------------------</pre><pre><strong>public</strong> <strong>class</strong> Bar {</pre><pre><strong>public</strong> Bar() {</pre><pre>System.out.println(<strong>this</strong> + &quot; created&quot;);</pre><pre>System.out.println(&quot;Bar ClassLoader: &quot; + <strong>this</strong>.getClass().getClassLoader());</pre><pre>}</pre><pre>@Override</pre><pre><strong>public</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println(<strong>this</strong> + &quot; finalized&quot;);</pre><pre>}</pre><pre>}</pre><p>After running this code output shows :</p><p>com.test.Bar@71bc1ae4 created<br>Bar ClassLoader: com.test.MyCustomClassLoader@71dac704<br>Test ClassLoader: com.test.MyCustomClassLoader@71dac704<br>com.test.Foo@650de12 finalized!</p><p>Now if we change the ThreadLocal variable to String in Foo.java code as</p><pre><strong>public</strong> <strong>class</strong> Foo {</pre><pre><strong>private</strong> <strong>static</strong> <strong>final</strong> ThreadLocal&lt;String&gt; tl = <strong>new</strong> ThreadLocal&lt;String&gt;();</pre><pre><strong>public</strong> Foo() {</pre><pre>Bar bar = <strong>new</strong> Bar();</pre><pre>tl.set(&quot;Hello&quot;);</pre><pre>System.out.println(&quot;Test ClassLoader: &quot; + <strong>this</strong>.getClass().getClassLoader());</pre><pre>}</pre><pre>@Override</pre><pre><strong>protected</strong> <strong>void</strong> finalize() {</pre><pre>System.out.println( <strong>this</strong> + &quot; finalized!&quot;);</pre><pre>}</pre><pre>}</pre><p>The output shows all the classes are GCed</p><p>com.test.Bar@71bc1ae4 created<br>Bar ClassLoader: com.test.MyCustomClassLoader@71dac704<br>Test ClassLoader: com.test.MyCustomClassLoader@71dac704<br>com.test.Bar@71bc1ae4 finalized<br>com.test.Foo@5d783be3 finalized!<br>*** CustomClassLoader finalized!</p><p>The reason behind is that Bar.class is loaded by MyCustomClassLoaders which means it has a reference.</p><p>current thread -&gt; Foo.tl -&gt; Bar.class -&gt; MyCustomClassLoader</p><p>But when we change to String then it uses Systemclassloader and has no reference to MyCustomClassLoader class</p><p>current thread -&gt; Foo.tl -&gt; String.class -&gt; System Class Loader</p><p>Now if we modify the Main class like this:</p><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String...args) <strong>throws</strong> Exception {</pre><pre>//loadClass();</pre><pre><strong>new</strong> Thread(<strong>new</strong> FutureTask(() -&gt; { loadClass(); <strong>return</strong> <strong>null</strong>; })).start();</pre><pre><strong>while</strong> (<strong>true</strong>) {</pre><pre>System.gc();</pre><pre>Thread.sleep(1000);</pre><pre>}</pre><pre>}</pre><p>All classes including classloader will be GCed, this is because we are asking the main thread to loadClass to a different Thread rather than the current thread (main).</p><p>Now let&#39;s look at the Threadlocal variable as shown in the Heap dump:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXJIEfbIly0204e3Ej6x1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUaATfco9jdnEq1bQl-smw.png" /></figure><p>In the above screenshots, it shows that the Bundle class loader is holding the reference of New Relic thread factory class which is using thread-local internally. And it is the same for most of the java.lang.ThreadLocal variable.</p><p>Current thread → New Relic Default Thread factory → OSGI Bundle class loader</p><p>In many enterprise applications, we use APM (Application performance management) agent which uses Java native library. In my case, we were using New Relic. As you can see in the above example, New Relic agent was holding the references and was not able to release the strong reference and hence caused an Out-of-Memory error in Metaspace.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c10e61e5e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache Query parameter in AWS Cloudfront — Part 1]]></title>
            <link>https://sumantapakira.medium.com/cache-query-parameter-in-aws-cloudfront-part-1-7ab49132b682?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab49132b682</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 12:56:45 GMT</pubDate>
            <atom:updated>2021-08-02T12:56:45.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cache Query parameter in AWS Cloudfront — Part 1</h3><p>There are 3 options in order to leverage Cloud-Front caching based on query parameters:</p><ul><li>None(Improve caching)</li><li>Forward All, Cache based on all</li><li>Forward All, Cache based on whitelist</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFnzSHQXfnr1apTn7kB-dw.png" /></figure><p>Let&#39;s see the advantage and disadvantages of each option</p><p><strong>None(Improve caching):</strong> When we select this option then the Cloud-Front does not forward any query parameter to the Origin server. For example, let&#39;s take this servlet as an example which takes the query param in the url and returns the JSON output with the parameter value: <a href="https://business-bt-com-dev-ams.digital-ent-int.bt.com/bin/servlets/cachetest.json?testparam=mytest53">https://your-server/bin/servlets/cachetest.json?testparam=mytest</a>-1</p><p>Here we will see the output as null</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI91vo3HbMoDGcfrHA_rpA.png" /></figure><p>Explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAaa2Tmc72lV3Xb-D58LFQ.png" /></figure><p>Advantage: This is useful for frontend react application where all code is executed on the browser and do not need to send parameter to the backend server.</p><p>Disadvantage: This is not suitable for AEM applications where we need to process requests based on query parameters. For example, a search request will not bring any result because the underlaying servlet expects query parameter value.</p><p><strong>Forward All, Cache based on all:</strong> Cloud-Front forwards all the query parameters to the origin server. This means we have to allow query parameters in the origin server i.e in the Dispatcher ignoreUrl parameter so that Apache can set Cache-Control header to the requested URL. If we do not allow in dispatcher then we will always get 200 HTTP code and Cache Miss from Cloud-Front because there will be no Cache-Control header added to the response. And Cache-Control header is added after dispatcher passes the ignoreUrl parameter check, if ignoreUrl is not whitelisted then the dispatcher will always send request AEM. We should also enable TTL in the dispatcher otherwise we will get old cached response from the dispatcher cache even though Cache-Control value is expired.</p><p>This option is useful if the origin server returns different versions of the response for all query string parameters. For example, this url: <a href="https://business-bt-com-dev-ams.digital-ent-int.bt.com/bin/servlets/cachetest.json?testparam=param-a&amp;time=true">https://your-server/bin/servlets/cachetest.json?testparam=1&amp;time=true</a>. In this servlet it takes two query params, first it takes the value of testparam and returns 10 times the value, and the second param if true then returns the current timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUYIZe4-g77CxPxVLZeGAg.png" /></figure><p><strong>Forward All, Cache based on the whitelist: </strong>If the origin server returns different versions of the response based on one or more query string parameters, then specify the parameters that we want CloudFront to use as a basis for caching. What it means is that in our previous URL example: <a href="https://business-bt-com-dev-ams.digital-ent-int.bt.com/bin/servlets/cachetest.json?testparam=param-a&amp;time=true">https://your-server/bin/servlets/cachetest.json?testparam=1&amp;time=true</a> , we have two request parameters, i.e testparam and time and we expect the response to be different based on the parameter value. For example, if testparam=3 then the output should be “Hello word: 30” and if time=false then TimeStamp will not be shown. That means output changes based on the query params.</p><p>Now let&#39;s suppose we have a requirement where we want only to consider ‘testparam’ query parameter, and we do not care whether ‘time’ parameter value is true or false. So we whitelist this ‘testparam’ in Cloud-Front distribution. This means Cloud-Front will maintain cache when query param ‘testparam’ is present in a subsequent request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTMp1vbx_4D7mjGXK6zUjw.png" /></figure><p>Recommendation:</p><ul><li>The first option: None (Improve caching) should not be used because we have many request parameter which needs to be sent to AEM</li><li>We have to allow ignoreUrl parameter in the dispatcher otherwise Cache-Control header cannot be set by Apache. One possibility is that we can set Cache-Control via AEM Sling filter and the dispatcher will create a header file (en.html.h) and add Cache-Control info inside of it but in this case, we have to maintain a separate list of allowed parameters which is not very good in terms of maintainability.</li><li>The query parameter value should be always in lowercase because for example a parameter ?color=Red and ?color=red will cause Cloud-Front to cache two different objects. Our code should always support lower-case and to make sure values entered by the end-users are always in lowercase, we need to write Lambda@Edge to pass lowercase always to the origin server.</li><li>My suggestion will be to use “Forward all, cache based on all” because we do not have to maintain a separate list of allowed query parameters, and also most importantly if we do not know the query parameters and have 301 redirects then we will get an infinite loop, more details <a href="https://wiki.intdigital.ee.co.uk/display/SME/301+Redirect+issue+analysis">here</a>:</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab49132b682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How CDN caching works]]></title>
            <link>https://sumantapakira.medium.com/how-cdn-caching-works-9c5d8b5ca2d5?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5d8b5ca2d5</guid>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 12:30:04 GMT</pubDate>
            <atom:updated>2021-08-03T08:49:11.009Z</atom:updated>
            <content:encoded><![CDATA[<p>Let&#39;s first understand how caching works behind the scene, lets consider you open your browser at 9:00 AM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOydLf6TLZg7RREOfoCvqg.png" /></figure><p>Note: We should either use Cache-Control or Expire header. We do not need both at the same time. All modern CDN providers use the Cache-Control header as primary, so in our case, we should use Cache-Control. Having Expires header will not make any difference if the Cache-Control header is already present.</p><p>Similarly using both Etag and Last-Modified is of no use. We should use either one of them. In our AEM case, we should use Last-Modified, this is because Etag has a compression issue in Apache. Apache uses gzip compression and adds something like this “2dc51–5beaacb536de4-gzip”. Because of this issue, we get 200 HTTP code instead of 304 even though there is no new content. This is not the same for the Node.js applications.</p><p>To overcome the above problem we could add the following code in this file in vhost file</p><p>RequestHeader edit &quot;If-None-Match&quot; &quot;^\&quot;(.*)-gzip\&quot;$&quot; &quot;\&quot;$1\&quot;&quot;</p><p>Header edit &quot;ETag&quot; &quot;^\&quot;(.*[^g][^z][^i][^p])\&quot;$&quot; &quot;\&quot;$1-gzip\&quot;&quot;</p><p>The above solution works but it does not solve redundancy issue. So I would suggest not to use the above code and use the below code:</p><p>Header unset ETag</p><p>Header unset Expires</p><p>FileETag None</p><p>When you press F5 in Chrome, it will <em>always</em> send requests to the server. These will be made with the Cache-Control:max-age=0 header. The server will usually respond with a 304 (Not Changed) status code. But we could also get 200 when there is new Etag/Last-Modified header.</p><p>When you press Ctrl+F5 or Shift+F5, the same requests are performed, but with the Cache-Control:no-cache header, thus forcing the server to send an uncached version, usually with a 200 (OK) status code. Here it could be possible that we get Cache Hit and not the updated content because cache-control header is not expired.</p><p>The <strong>Age</strong> header is a AWS Cliudfront specific and tells how many seconds the content is sitting in the cache. If the Age value is greater than max-age and if origin sends back either 200/304 then it reset to 0 again.</p><p><em>What will happen if there is no “cache-control” or “expiries” headers are present?</em></p><p>The html page will be cached forever in the browser and will get 304, until cache is cleared manually by hard refresh. In this case, Age header value will keep on increase, and it will be 0 once cache is removed from Cloudfront.</p><p>In our current setup we always get updated CSS/JS/images, the reason is because we do not have HTML caching enabled. As a result every time CDN goes to Origin server (Apache) which returns HTML with updated css/js/image because image/css/js are part of HTML content tag.</p><p>Please continue to the next part <a href="https://sumantapakira.medium.com/cache-query-parameter-in-aws-cloudfront-part-1-7ab49132b682">https://sumantapakira.medium.com/cache-query-parameter-in-aws-cloudfront-part-1-7ab49132b682</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5d8b5ca2d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AEM Field based inheritance]]></title>
            <link>https://sumantapakira.medium.com/aem-field-based-inheritance-8b8ba5cd9502?source=rss-960b13202097------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8ba5cd9502</guid>
            <category><![CDATA[aem]]></category>
            <category><![CDATA[touch-ui]]></category>
            <dc:creator><![CDATA[Sumanta pakira]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 23:15:39 GMT</pubDate>
            <atom:updated>2020-12-07T23:16:13.278Z</atom:updated>
            <content:encoded><![CDATA[<p>AEM Field based inheritance</p><p><a href="https://github.com/sumantapakira/touch-ui-field-based-inheritance">https://github.com/sumantapakira/touch-ui-field-based-inheritance</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8ba5cd9502" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>