In this section
- Data Centre Covenant render · legislation / research/repd-top-100-2026-11-28/data-centre-covenant.html lines 701–1050
- Test Track test · legislation / tracking/test_track.py lines 1–83
- Track ingest · legislation / tracking/track.py lines 1–185
Data Centre Covenant
A web page in the research folder of Legislation that draws autocomplete. Published at https://ventusltd.github.io/legislation/research/repd-top-100-2026-11-28/data-centre-covenant.html. It is built from the spam capture helper (`spamCapture`).
renderlegislation / research/repd-top-100-2026-11-28/data-centre-covenant.html · lines 701–1050 of 1050 (continued from section 977) · Entry point
- What it does
- It draws autocomplete. Defines spamCapture. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file autocomplete.json; form fields (user input). Out: web page; SVG drawing.
- Downstream impact
- Used directly by 1 file: Legislation — Legal Evidence Page (legislation, https://ventusltd.github.io/legislation/legal-evidence/). Reached from 20 other entry points, including GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report A4 (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/); Report Model (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). It is itself an entry point, published at https://ventusltd.github.io/legislation/research/repd-top-100-2026-11-28/data-centre-covenant.html.
- What it achieves
- Defines `spamCapture`. Its code works with 6 GW. It responds to DOMContentLoaded and submit events.
- Why it matters
- Loaded by the Legal Evidence page at https://ventusltd.github.io/legislation/legal-evidence/.
- Application
- legislation · research/repd-top-100-2026-11-28 · page
- Uses
- /assets/frontend/govuk_publishing_components/vendor/lux/lux-measurer-d66192b1b665d415e1874e49a48138b7ae339548aa6cdb8687c7f9933e72b969.js, /assets/frontend/govuk_publishing_components/rum-custom-data-b9e1806d1da2fa8ef1855d01aa71ba5eb0afc010dd2c4de3672cc7c7a39b0c8c.js, /assets/frontend/govuk_publishing_components/rum-loader-a65b10e18ceeba3bd8a2eac507c7f2c513cdc82f35097df903fdea87f1dc2e33.js, /assets/frontend/govuk_publishing_components/load-analytics-d5c92d4ce9f98141170a466427da86ca1ff62f234637bf0776121e6df57b3b67.js, /assets/frontend/application-6996f83d6fb61f85eeb080c9a6db75bbca843dc8bfb47ed803563ae21e7b80e1.css, /assets/frontend/views/_html-publication-d183ff6655d34a5cea8d3f6f863d5b6c74654d40325c0a970e8e96ca046b4d07.css, /assets/frontend/views/_csv_preview-ddf66f9f13d0fb5e8672480d53d092910344fca34f35e21fc2220e1500143904.css, /assets/frontend/application-8fe64fc846ff6c349839e73b01a76d3fbc373d266f1f8ef7a9fc749440eed2b0.js
- Used by
- linked from Legislation — Legal Evidence Page (link)
- Produces
- spamCapture
- Defines here
- spamCapture
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 research/repd-top-100-2026-11-28/data-centre-covenant.html:701-1050 · blob 087ae1effd2728bf0a788a18e5d733edc576599d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
<p>For sites that demonstrate sufficient strategic value, the government will:</p>
<ul>
<li>reserve and reallocate connections. The Government will use new powers in the Planning and Infrastructure Act to prioritise strategically important demand projects, including data centres, by reserving future capacity and reallocating capacity released when other projects leave the connections queue. This will help strategically important projects, including data centres, access grid capacit … [line shortened here: 445 characters; full line on GitHub]
<li>identify additional capacity. The Government will work with NESO and the network companies to identify locations where capacity may be available before 2030 and may use Planning and Infrastructure Act powers to enable strategically important data centres and other strategically important projects to access this capacity.</li>
<li>accelerate connections before 2030. Where there is a need to go further, the Government will use Planning and Infrastructure Act powers to facilitate transfer of pre-2030 data centre connections contracts to strategically important data centres, to secure access to power in this critical period for the development of AI. </li>
<li>enable access to temporary power to bridge the gap to grid connections. The Government will develop a tightly controlled framework to permit on site generation until a grid connection can be secured. This will only be available for exceptionally strategic projects, only where the measures set out above cannot secure the required capacity in time, and subject to conditions such as ensuring en … [line shortened here: 419 characters; full line on GitHub]
</ul>
<p>The government will set out further details in due course on the definition of strategic data centres and the additional criteria such projects will be expected to meet.</p>
<p>In addition, the government is moving forward with wider reforms to support viable projects to build faster and with more certainty while meeting expectations to support sustainable growth, protect communities, and conserve resources. The government will:</p>
<ul>
<li>move forward with the strategic alignment of data-centre grid connections to regional infrastructure targets beyond 2030, informed by the ALIGN spatial planning tool, to secure vital capacity while balancing the needs of the energy system and other relevant constraints including water and land.</li>
<li>support greater choice for developers to self-build connection infrastructure, subject to appropriate consumer and system protections;</li>
<li>develop ways for data centres to connect more flexibly to the system and develop backstop operational control measures that enable more data centre demand to connect while keeping the system secure;</li>
<li>support implementation of Ofgem’s data-centre commitment fee and queue management measures to deter speculative demand, and free up connection capacity for viable projects;</li>
<li>publish the draft Data Centre National Policy Statement for consultation, which sets out the decision-making framework for data centre projects seeking development consent through the Nationally Significant Infrastructure Project regime. This framework will establish a progressive vision for harnessing this investment, ensuring that data centre growth delivers clean energy, skilled jobs, and … [line shortened here: 487 characters; full line on GitHub]
<li>encourage all operators to use energy and water efficiently and publish annual data on total and peak water and power use, as set out in the Written Ministerial Statement on Enabling Sustainable Data Centre Growth Through Responsible Water and Energy Use;</li>
<li>continue to deliver the five AI Growth Zones across England, Scotland and Wales to accelerate planning and infrastructure delivery for AI capacity.</li>
</ul>
<p>This Covenant sets out a clear offer: government will support faster and more certain delivery of the data centres the country needs in return for responsible development that delivers lasting benefits for communities. Together, these measures will help keep more of the benefits of AI in Britain, supported by infrastructure that serves our long-term interests.</p>
</div>
</div></div>
</div>
</div>
<div class="govuk-grid-row back-to-top-wrapper">
<a class="govuk-link gem-c-back-to-top-link govuk-!-display-none-print" href="#contents">
<svg class="gem-c-back-to-top-link__icon" xmlns="http://www.w3.org/2000/svg" width="13" height="17" viewBox="0 0 13 17" aria-hidden="true" focusable="false">
<path fill="currentColor" d="M6.5 0L0 6.5 1.4 8l4-4v12.7h2V4l4.3 4L13 6.4z" />
</svg>
Back to top
</a>
</div>
</div>
</main>
</div>
<div class="govuk-width-container">
<div data-module="feedback ga4-event-tracker" class="gem-c-feedback govuk-!-display-none-print">
<div class="gem-c-feedback__prompt gem-c-feedback__js-show js-prompt" tabindex="-1">
<div class="gem-c-feedback__prompt-content">
<div class="gem-c-feedback__prompt-questions js-prompt-questions" hidden>
<div class="gem-c-feedback__prompt-question-answer">
<h2 class="gem-c-feedback__prompt-question">Is this page useful?</h2>
<ul class="gem-c-feedback__option-list">
<li class="gem-c-feedback__option-list-item govuk-visually-hidden" hidden>
<a class="gem-c-feedback__prompt-link" role="button" hidden="hidden" href="/contact/govuk">
Maybe
</a> </li>
<li class="gem-c-feedback__option-list-item">
<button class="govuk-button gem-c-feedback__prompt-link js-page-is-useful" data-ga4-event='{"event_name":"form_submit","type":"feedback","text":"Yes","section":"Is this page useful?","tool_name":"Is this page useful?"}'>
Yes <span class="govuk-visually-hidden">this page is useful</span>
</button> </li>
<li class="gem-c-feedback__option-list-item">
<button class="govuk-button gem-c-feedback__prompt-link js-toggle-form js-page-is-not-useful" aria-controls="page-is-not-useful" data-ga4-event='{"event_name":"form_submit","type":"feedback","text":"No","section":"Is this page useful?","tool_name":"Is this page useful?"}'>
No <span class="govuk-visually-hidden">this page is not useful</span>
</button> </li>
</ul>
</div>
</div>
<div class="gem-c-feedback__prompt-questions gem-c-feedback__prompt-success js-prompt-success" role="alert" hidden>
Thank you for your feedback
</div>
<div class="gem-c-feedback__prompt-questions gem-c-feedback__prompt-questions--something-is-wrong js-prompt-questions" hidden>
<button class="govuk-button gem-c-feedback__prompt-link js-toggle-form js-something-is-wrong" aria-controls="something-is-wrong" data-ga4-event='{"event_name":"form_submit","type":"feedback","text":"Report a problem with this page","section":"Is this page useful?","tool_name":"Is this page useful?"}'>
Report a problem with this page
</button> </div>
</div>
</div>
<form action="/contact/govuk/problem_reports"
id="something-is-wrong"
class="gem-c-feedback__form js-feedback-form"
method="post"
hidden>
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds">
<div class="gem-c-feedback__error-summary gem-c-feedback__js-show js-errors" tabindex="-1" hidden></div>
<input type="hidden" name="url" value="https://www.gov.uk/government/publications/data-centre-covenant/the-data-centre-covenant">
<h2 class="gem-c-feedback__form-heading">Help us improve GOV.UK</h2>
<p id="feedback_explanation" class="gem-c-feedback__form-paragraph">Do not include personal or financial information like your National Insurance number or credit card details.</p>
<div class="govuk-visually-hidden" aria-hidden="true">
<label for="giraffe">This field is for robots only. Please leave blank</label>
<input id="giraffe" name="giraffe" type="text" pattern=".{0}" tabindex="-1" autocomplete="off">
</div>
<div class="gem-c-textarea govuk-form-group govuk-!-margin-bottom-6">
<label for="textarea-5696b771" class="gem-c-label govuk-label">What were you doing?</label>
<textarea name="what_doing" class="govuk-textarea" id="textarea-5696b771" rows="3" spellcheck="true" aria-describedby="feedback_explanation">
</textarea>
</div>
<div class="gem-c-textarea govuk-form-group govuk-!-margin-bottom-6">
<label for="textarea-7ced9729" class="gem-c-label govuk-label">What went wrong?</label>
<textarea name="what_wrong" class="govuk-textarea" id="textarea-7ced9729" rows="3" spellcheck="true">
</textarea>
</div>
<div class="gem-c-feedback__button-wrapper">
<button class="gem-c-button govuk-button govuk-!-margin-bottom-6" type="submit" data-ga4-event='{"event_name":"form_submit","type":"feedback","text":"Send","section":"Help us improve GOV.UK","tool_name":"Help us improve GOV.UK"}'>Send</button>
<button class="gem-c-button govuk-button gem-c-button--secondary-quiet govuk-!-margin-bottom-0 js-close-form" type="submit" aria-controls="something-is-wrong">Cancel</button>
</div>
</div>
</div>
</form>
<script nonce="ZXk3nmjcAutlxjkNznyJ8w==">
//<![CDATA[
document.addEventListener("DOMContentLoaded", function () {
var input = document.querySelector("#giraffe"),
form = document.querySelector("#something-is-wrong")
form.addEventListener("submit", spamCapture);
function spamCapture(e) {
if (input.value.length !== 0) return;
e.preventDefault();
}
});
//]]>
</script>
<div id="page-is-not-useful" class="gem-c-feedback__form gem-c-feedback__form--email gem-c-feedback__js-show js-feedback-form">
<div class="govuk-grid-row">
<div class="govuk-grid-column-two-thirds" id="survey-wrapper">
<div class="gem-c-feedback__error-summary js-errors" tabindex="-1" hidden></div>
<h2 class="gem-c-feedback__form-heading">Help us improve GOV.UK</h2>
<p id="survey_explanation" class="gem-c-feedback__form-paragraph">
To help us improve GOV.UK, we’d like to know more about your visit today.
<a href="https://www.smartsurvey.co.uk/s/gov-uk-banner/?c=no-js" class="govuk-link" target="_blank" rel="noopener noreferrer external">Please fill in this survey (opens in a new tab<noscript> and requires JavaScript</noscript>)</a>.
</p>
<div class="gem-c-feedback__close">
<button class="gem-c-button govuk-button gem-c-button--secondary-quiet govuk-!-margin-bottom-6 js-close-form" type="submit" aria-controls="page-is-not-useful">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
<footer data-module="ga4-link-tracker" class="gem-c-layout-footer govuk-footer">
<div class="govuk-width-container">
<svg
xmlns="http://www.w3.org/2000/svg"
focusable="false"
role="presentation"
viewBox="0 0 64 60"
height="30"
width="32"
fill="currentcolor"
class="govuk-footer__crown">
<g>
<circle cx="20" cy="17.6" r="3.7"></circle>
<circle cx="10.2" cy="23.5" r="3.7"></circle>
<circle cx="3.7" cy="33.2" r="3.7"></circle>
<circle cx="31.7" cy="30.6" r="3.7"></circle>
<circle cx="43.3" cy="17.6" r="3.7"></circle>
<circle cx="53.2" cy="23.5" r="3.7"></circle>
<circle cx="59.7" cy="33.2" r="3.7"></circle>
<circle cx="31.7" cy="30.6" r="3.7"></circle>
<path d="M33.1,9.8c.2-.1.3-.3.5-.5l4.6,2.4v-6.8l-4.6,1.5c-.1-.2-.3-.3-.5-.5l1.9-5.9h-6.7l1.9,5.9c-.2.1-.3.3-.5.5l-4.6-1.5v6.8l4.6-2.4c.1.2.3.3.5.5l-2.6,8c-.9,2.8,1.2,5.7,4.1,5.7h0c3,0,5.1-2.9,4.1-5.7l-2.6-8ZM37,37.9s-3.4,3.8-4.1,6.1c2.2,0,4.2-.5,6.4-2.8l-.7,8.5c-2-2.8-4.4-4.1-5.7-3.8.1,3.1.5,6.7,5.8,7.2,3.7.3,6.7-1.5,7-3.8.4-2.6-2-4.3-3.7-1.6-1.4-4.5,2.4-6.1,4.9-3.2-1.9-4.5-1.8-7.7,2.4-10. … [line shortened here: 1,068 characters; full line on GitHub]
</g>
</svg>
<div class="govuk-footer__navigation">
<div class="govuk-grid-column-two-thirds govuk-!-display-none-print">
<h2 class="govuk-footer__heading govuk-heading-m">Services and information</h2>
<ul class="govuk-footer__list govuk-footer__list--columns-2">
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"1","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/benefits">Benefits</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"2","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/births-deaths-marriages">Births, death, marriages and care</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"3","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/business">Business and self-employed</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"4","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/childcare-parenting">Childcare and parenting</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"5","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/citizenship">Citizenship and living in the UK</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"6","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/justice">Crime, justice and the law</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"7","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/disabilities">Disabled people</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"8","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/driving">Driving and transport</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"9","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/education">Education and learning</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"10","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/employing-people">Employing people</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"11","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/environment-countryside">Environment and countryside</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"12","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/housing-local-services">Housing and local services</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"13","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/tax">Money and tax</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"14","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/abroad">Passports, travel and living abroad</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"15","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/visas-immigration">Visas and immigration</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"16","index_section":"1","index_section_count":"5","index_total":"16","section":"Services and information"}' href="/browse/working">Working, jobs and pensions</a>
</li>
</ul>
</div>
<div class="govuk-grid-column-one-third govuk-!-display-none-print">
<h2 class="govuk-footer__heading govuk-heading-m">Government activity</h2>
<ul class="govuk-footer__list govuk-footer__list--columns-1">
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"1","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/government/organisations">Departments</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"2","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/search/news-and-communications">News</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"3","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/search/guidance-and-regulation">Guidance and regulation</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"4","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/search/research-and-statistics">Research and statistics</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"5","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/search/policy-papers-and-consultations">Policy papers and consultations</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"6","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/search/transparency-and-freedom-of-information-releases">Transparency</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"7","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/government/how-government-works">How government works</a>
</li>
<li class="govuk-footer__list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"8","index_section":"2","index_section_count":"5","index_total":"8","section":"Government activity"}' href="/government/get-involved">Get involved</a>
</li>
</ul>
</div>
</div>
<hr class="govuk-footer__section-break govuk-!-display-none-print">
<div class="govuk-footer__meta">
<div class="govuk-footer__meta-item govuk-footer__meta-item--grow">
<h2 class="govuk-visually-hidden">Support links</h2>
<ul class="govuk-footer__inline-list govuk-!-display-none-print">
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"1","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/help">Help</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"2","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/help/privacy-notice">Privacy</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"3","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/help/cookies">Cookies</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"4","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/help/accessibility-statement">Accessibility statement</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"5","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/contact">Contact</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"6","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/help/terms-conditions">Terms and conditions</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" lang="cy" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"7","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/cymraeg">Rhestr o Wasanaethau Cymraeg</a>
</li>
<li class="govuk-footer__inline-list-item">
<a class="govuk-footer__link" data-ga4-link='{"event_name":"navigation","type":"footer","index_link":"8","index_section":"3","index_section_count":"5","index_total":"8","section":"Support links"}' href="/government/organisations/government-digital-service">Government Digital Service</a>
</li>
</ul>
<svg aria-hidden="true" focusable="false" class="govuk-footer__licence-logo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 483.2 195.7" height="17" width="41">
<path
fill="currentColor"
d="M421.5 142.8V.1l-50.7 32.3v161.1h112.4v-50.7zm-122.3-9.6A47.12 47.12 0 0 1 221 97.8c0-26 21.1-47.1 47.1-47.1 16.7 0 31.4 8.7 39.7 21.8l42.7-27.2A97.63 97.63 0 0 0 268.1 0c-36.5 0-68.3 20.1-85.1 49.7A98 98 0 0 0 97.8 0C43.9 0 0 43.9 0 97.8s43.9 97.8 97.8 97.8c36.5 0 68.3-20.1 85.1-49.7a97.76 97.76 0 0 0 149.6 25.4l19.4 22.2h3v-87.8h-80l24.3 27.5zM97.8 145c-26 0-47.1-21.1-47.1-47.1s … [line shortened here: 458 characters; full line on GitHub]
</svg>
<span
class="govuk-footer__licence-description"
data-ga4-link='{"event_name":"navigation","section":"Licence","index_section":"4","index_link":"1","index_section_count":"5","text":"Open Government Licence v3.0","index_total":"1","type":"footer"}'>
All content is available under the <a class="govuk-footer__link" href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated
</span>
</div>
<div
class="govuk-footer__meta-item"
data-ga4-link='{"event_name":"navigation","section":"Copyright","index_section":"5","index_link":"1","index_section_count":"5","text":"© Crown copyright","index_total":"1","type":"footer"}'>
<a class="govuk-footer__link govuk-footer__copyright-logo" href="https://www.nationalarchives.gov.uk/information-management/re-using-public-sector-information/uk-government-licensing-framework/crown-copyright/">© Crown copyright</a>
</div>
</div>
</div>
</footer>
<script src="/assets/frontend/application-8fe64fc846ff6c349839e73b01a76d3fbc373d266f1f8ef7a9fc749440eed2b0.js" type="module"></script>
</body></html>Test Track
A test in the tracking folder of Legislation that checks Track. It sets up (`setUp`) and runs once (`run_once`).
testlegislation / tracking/test_track.py · lines 1–83 of 83 · Entry point · pattern run_once (shared by 4 files)
- What it does
- It tests its inputs. Defines 12 functions or classes, including TrackerTests, setUp, response, run_once, test_versions_and_reversion. Uses libraries json, tempfile, unittest, pathlib, unittest.mock. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file sources.json; JSON file checkpoint.json; JSON file b.json.
- Downstream impact
- Used directly by 1 file: Tracking Workflow (legislation).
- What it achieves
- Defines `TrackerTests`, `setUp`, `response` and 9 more.
- Why it matters
- Run by Tracking Workflow.
- Application
- legislation · tracking · test
- Uses
- Track (import), json, tempfile, unittest, pathlib, unittest.mock, urllib.error
- Used by
- run by Tracking Workflow (workflow run)
- Produces
- TrackerTests
- Defines here
- TrackerTests, setUp, response, run_once, test_versions_and_reversion, test_conditional_and_digest, test_malformed_source_preserves_checkpoint, test_gap_and_bad_url, test_budget_preserves_old_receipts, test_atom_selects_relevant_legislation, test_failures_are_isolated, getter
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 tracking/test_track.py:1-83 · blob e14b25b6d96e5101aa90a9cf467387d355404aff · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
from urllib.error import HTTPError
import track
class TrackerTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.source = json.loads((track.HERE / "sources.json").read_bytes())[2]
def response(self, title="Energy consultation", link="/government/test"):
body = {"results":[{"title":title, "link":link, "content_store_document_type":"open_consultation",
"public_timestamp":"2026-01-02T12:00:00Z"}]}
return 200, {"ETag":'"abc"'}, json.dumps(body).encode()
def run_once(self, stamp, response):
return track.run(self.root, [self.source], stamp, Mock(return_value=response))["sources"][self.source["id"]]
def test_versions_and_reversion(self):
a = self.run_once("a", self.response())
self.assertTrue(a["initial"])
b = self.run_once("b", self.response("Revised consultation"))
c = self.run_once("c", self.response())
self.assertEqual(b["changes"][0]["previous_window_version"], a["changes"][0]["version"])
self.assertEqual(c["changes"][0]["version"], a["changes"][0]["version"])
self.assertEqual(len(list((self.root/"objects").rglob("*.json"))),2)
self.assertEqual(len(list((self.root/"receipts").glob("*.json"))),3)
def test_conditional_and_digest(self):
self.run_once("a", self.response())
self.assertEqual(self.run_once("b", self.response())["state"],"same_digest")
self.assertEqual(self.run_once("c", (304,{},b""))["state"],"not_modified")
error = HTTPError(self.source["url"], 304, "", {}, None)
with patch.object(track, "urlopen", side_effect=error) as opened:
result = track.fetch(self.source["url"], {"etag":'"abc"',"body_sha256":"stored"})
self.assertEqual(result[0], 304)
self.assertEqual(dict(opened.call_args.args[0].header_items())["If-none-match"], '"abc"')
def test_malformed_source_preserves_checkpoint(self):
self.run_once("a", self.response())
checkpoint = (self.root / "checkpoint.json").read_bytes()
self.assertEqual(self.run_once("b", (200,{},b"<html>"))["state"],"failed")
self.assertEqual((self.root / "checkpoint.json").read_bytes(),checkpoint)
def test_gap_and_bad_url(self):
self.run_once("a", self.response())
self.assertTrue(self.run_once("b",self.response(link="/different"))["window_gap_possible"])
self.assertEqual(self.run_once("c",self.response(link="https://example.com/item"))["state"],"failed")
def test_budget_preserves_old_receipts(self):
self.run_once("a", self.response())
with patch.object(track, "MAX_ARCHIVE", 100), self.assertRaisesRegex(ValueError, "watermark"):
self.run_once("b", self.response("Changed"))
self.assertFalse((self.root/"receipts/b.json").exists())
def test_atom_selects_relevant_legislation(self):
source = json.loads((track.HERE / "sources.json").read_bytes())[0]
body = b'<feed xmlns="http://www.w3.org/2005/Atom"><entry><id>http://www.legislation.gov.uk/id/uksi/2020/1</id><title type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><span>Electricity Act (Commencement) Order</span> / <span>Gorchymyn</span></div></title></entry><entry><id>http://www.legislation.gov.uk/id/uksi/2020/2</id><title>Bicycles</title></entry></feed>'
receipt = track.run(self.root, [source], "a", lambda u,p:(200,{},body))
self.assertEqual(receipt["sources"][source["id"]]["relevant"],1)
obj = next((self.root / "objects").rglob("*.json"))
self.assertEqual(json.loads(obj.read_bytes())["kind"],"commencement_title_candidate")
def test_failures_are_isolated(self):
other = dict(self.source, id="second", url="https://www.gov.uk/api/other")
def getter(url, previous):
if url == self.source["url"]:
raise OSError("temporarily unavailable")
return self.response()
receipt = track.run(self.root, [self.source, other], "one", getter)
self.assertEqual(receipt["sources"][other["id"]]["state"], "observed")
self.assertEqual(receipt["sources"][self.source["id"]]["state"], "failed")
if __name__ == "__main__":
unittest.main()Track
A Python command-line tool in the tracking folder of Legislation that fetches checkpoint and sources, using SHA-256.
ingestlegislation / tracking/track.py · lines 1–185 of 185 · Entry point · pattern observe (shared by 13 files)
- What it does
- It fetches checkpoint and sources. Defines 8 functions or classes, including encode, put, legal_link, parse, fetch. Uses libraries argparse, datetime, hashlib, json, os. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file checkpoint.json; JSON file sources.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: Test Track (legislation); Tracking Workflow (legislation).
- What it achieves
- It is built from the encode step (`encode`), the put step (`put`) and the legal link helper (`legal_link`). Observe official listing metadata. Source documents and legal status are separate evidence.
- Why it matters
- Run by Tracking Workflow. Checked by Test Track.
- Application
- legislation · tracking · Python CLI
- Uses
- argparse, datetime, hashlib, json, os, pathlib, re, socket
- Used by
- imported by Test Track (import), run by Tracking Workflow (workflow run)
- Produces
- encode, put, legal_link, parse, fetch, observe, run, main
- Defines here
- encode, put, legal_link, parse, fetch, observe, run, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- legislation@960afbd0f5393e818b400a7f1a523acd6814e217 tracking/track.py:1-185 · blob 7ab381635bf56c90cd23a68c98f18a2eb854799d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""Observe official listing metadata. Source documents and legal status are separate evidence."""
import argparse
from datetime import datetime, timezone
from hashlib import sha256
import json
import os
from pathlib import Path
import re
import socket
import sys
import tempfile
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, urlopen
from xml.etree import ElementTree as ET
HERE = Path(__file__).resolve().parent
MAX_RESPONSE = 1_048_576
MAX_ARCHIVE = 64 * 1024 * 1024
ATOM = "{http://www.w3.org/2005/Atom}"
SUBJECT = re.compile(
r"electric|energy|wind farm|solar|batter|substation|wayleave|easement|"
r"infrastructure|planning|environment|water|telecommunication|procurement|"
r"subsid|compulsory purchase|construction|health and safety|data cent", re.I
)
def encode(value):
return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
def put(path, data, immutable=False):
path.parent.mkdir(parents=True, exist_ok=True)
if immutable and path.exists():
if path.read_bytes() != data:
raise ValueError(f"immutable object mismatch: {path.name}")
return
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as tmp:
tmp.write(data)
os.replace(tmp.name, path)
def legal_link(url, host):
parsed = urlsplit(url)
if parsed.scheme not in ("http", "https") or parsed.netloc not in {host, host.removeprefix("www.")}:
raise ValueError("non-authoritative listing link")
return url
def parse(source, body):
host = urlsplit(source["url"]).netloc
rows = []
if source["parser"] == "atom":
root = ET.fromstring(body)
if root.tag != ATOM + "feed":
raise ValueError("unexpected feed type")
for entry in root.findall(ATOM + "entry"):
links = [el.get("href") for el in entry.findall(ATOM + "link")
if el.get("rel", "alternate") == "alternate" and el.get("href")]
identity = entry.findtext(ATOM + "id")
element = entry.find(ATOM + "title")
title = " ".join("".join(element.itertext()).split()) if element is not None else None
if not identity or not title:
raise ValueError("missing Atom id or title")
instrument = entry.findtext("{http://purl.org/dc/elements/1.1/}identifier")
locator = legal_link(urljoin(source["url"], links[0] if links else instrument or identity), host)
kind = source["category"]
if kind == "legislation_publication":
if "commencement" in title.lower():
kind = "commencement_title_candidate"
elif "amendment" in title.lower():
kind = "amendment_title_candidate"
rows.append({"identity":identity,"title":title,"url":locator,"kind":kind,
"publisher_timestamp":entry.findtext(ATOM + "updated") or entry.findtext(ATOM + "published")})
else:
payload = json.loads(body)
if not isinstance(payload.get("results"), list):
raise ValueError("unexpected search response")
for item in payload["results"]:
if not item.get("link") or not item.get("title"):
raise ValueError("missing GOV.UK title or link")
url = legal_link(urljoin(source["url"], item["link"]), host)
rows.append({"identity":url,"title":item["title"],"url":url,
"kind":item.get("content_store_document_type") or source["category"],
"publisher_timestamp":item.get("public_timestamp")})
if len(rows) > 250:
raise ValueError("listing exceeds entry limit")
return rows
def fetch(url, previous):
headers = {"User-Agent":"Ventus-Legislation/1.0 (+https://github.com/Ventusltd/legislation)"}
for key, header in [("etag","If-None-Match"), ("modified","If-Modified-Since")]:
if previous.get(key):
headers[header] = previous[key]
for attempt in range(2):
try:
with urlopen(Request(url, headers=headers), timeout=12) as response:
if urlsplit(response.geturl()).netloc != urlsplit(url).netloc:
raise ValueError("unexpected feed redirect")
body = response.read(MAX_RESPONSE + 1)
if len(body) > MAX_RESPONSE:
raise ValueError("response exceeds byte budget")
return 200, response.headers, body
except HTTPError as exc:
if exc.code == 304 and previous.get("body_sha256"):
return 304, {}, b""
if exc.code not in (500, 502, 503, 504) or attempt == 1 or exc.headers.get("Retry-After"):
raise
except (URLError, socket.timeout):
if attempt == 1:
raise
time.sleep(1)
def observe(root, source, previous, getter=fetch):
if previous.get("url") != source["url"]:
previous = {}
code, headers, body = getter(source["url"], previous)
if code == 304:
return previous, {"state":"not_modified","response_bytes":0}
digest = sha256(body).hexdigest()
current = {**previous, "url":source["url"], "etag":headers.get("ETag"),
"modified":headers.get("Last-Modified"), "body_sha256":digest}
if previous.get("body_sha256") == digest:
return current, {"state":"same_digest","response_bytes":len(body)}
rows = parse(source, body)
ids = [sha256(item["identity"].encode()).hexdigest() for item in rows]
overlap = set(ids).intersection(previous.get("window", []))
changes = []
current_versions = {}
for identity, row in zip(ids, rows):
if source["filter_subject"] and not SUBJECT.search(row["title"]):
continue
data = encode({"source":source["id"], **row})
version = sha256(data).hexdigest()
current_versions[identity] = version
path = root / "objects" / version[:2] / (version + ".json")
if previous.get("versions", {}).get(identity) != version:
put(path, data, immutable=True)
changes.append({"id":identity,"previous_window_version":previous.get("versions",{}).get(identity),
"version":version})
current.update(window=ids, versions=current_versions)
return current, {"state":"observed","listing_sha256":digest,"response_bytes":len(body),
"listed":len(rows),"relevant":len(current_versions),"initial":not previous,
"window_gap_possible":bool(previous.get("window")) and not overlap,"changes":changes}
def run(root, sources, stamp, getter=fetch):
checkpoint = root / "checkpoint.json"
old = json.loads(checkpoint.read_bytes()) if checkpoint.exists() else {}
new = dict(old)
results = {}
archive_bytes = sum(p.stat().st_size for p in root.rglob("*.json"))
# Reserve the full bounded attempt before writing any new object.
reserve = (len(sources) * MAX_RESPONSE * 4) + MAX_RESPONSE
if archive_bytes + reserve > MAX_ARCHIVE:
raise ValueError("journal storage watermark reached; retain history and review capacity")
for source in sources:
key = source["id"]
try:
new[key], results[key] = observe(root, source, old.get(key, {}), getter)
except (OSError, ValueError, KeyError, ET.ParseError) as exc:
results[key] = {"state":"failed","error":str(exc)[:200]}
receipt = {"observed_at":stamp,"sources":results,"evidence_kind":"listing_metadata"}
name = stamp.replace(":", "-")
put(root / "receipts" / (name + ".json"), encode(receipt), immutable=True)
put(checkpoint, encode(new))
return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("archive", type=Path)
args = parser.parse_args()
sources = json.loads((HERE / "sources.json").read_bytes())
stamp = datetime.now(timezone.utc).isoformat(timespec="microseconds")
receipt = run(args.archive, sources, stamp)
print(json.dumps({k:v["state"] for k,v in receipt["sources"].items()}, sort_keys=True))
return int(any(v["state"] == "failed" for v in receipt["sources"].values()))
if __name__ == "__main__":
sys.exit(main())